无法将标签添加到python Tkin

2024-03-29 00:00:02 发布

您现在位置:Python中文网/ 问答频道 /正文

当我按下python窗体上的按钮时,我想添加新标签并将其放在网格上。当我按下按钮时,什么也没发生。你知道吗

我的代码随附:

from Tkinter import *

class Application(Frame):

    def __init__(self,master):
        Frame.__init__(self,master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        topiclbl = Label(self,text = 'Enter topic for search',font=(12))
        topiclbl.grid()
        topictxt = Text(self,height=1, width=30,font=(12))
        topictxt.grid()
        searchbtn = Button(self,text = 'Search Videos',command='search')
        searchbtn.grid()

    def search(self):

        message = 'Searching...'
        self.topictxt.insert(0.0,message)
        searchlbl = Label(self,text = message,font=(12))
        searchlbl.grid()


root = Tk()
root.title('Video Search')
root.geometry('600x600')
app=Application(root)
root.mainloop()

Tags: textselfmastermessagesearchapplicationinitdef
2条回答

代码中有几个问题:

您在command参数中引用了错误的方法名,应该是:

searchbtn = Button(self,text = 'Search Videos',command=self.search)

另外,您还有一些属性问题:

不能在此方法之外访问在create_widget方法中定义的topictxt,除非将其作为实例属性,方法如下:

self.topiclbl = Label(self,text = 'Enter topic for search',font=(12))。。。其余的也一样。为了解决这个问题:

class Application(Frame):

    def __init__(self,master):
        Frame.__init__(self,master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        self.topiclbl = Label(self,text = 'Enter topic for search',font=(12))
        self.topiclbl.grid()
        self.topictxt = Text(self,height=1, width=30,font=(12))
        self.topictxt.grid()
        self.searchbtn = Button(self,text = 'Search Videos',command=self.search)
        self.searchbtn.grid()

    def search(self):

        message = 'Searching...'
        self.topictxt.insert(0.0,message)
        self.searchlbl = Label(self,text = message,font=(12))
        self.searchlbl.grid()

另一种方法是使用lambda传递所需的对象(标签):

class Application(Frame):

    def __init__(self,master):
        Frame.__init__(self,master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        topiclbl = Label(self,text = 'Enter topic for search',font=(12))
        topiclbl.grid()
        topictxt = Text(self,height=1, width=30,font=(12))
        topictxt.grid()
        searchbtn = Button(self,text = 'Search Videos',command=lambda: self.search(topictxt))
        searchbtn.grid()

    def search(self, wdgt):

        message = 'Searching...'
        wdgt.insert(0.0,message)
        searchlbl = Label(self,text = message,font=(12))
        searchlbl.grid()

创建函数时,应该将实际函数传递给Button

例如

searchbtn = Button(self,text = 'Search Videos',command=self.search)

相关问题 更多 >