Can';t向python Tkinter添加标签
当我按下python表单上的按钮时,我想添加新标签并将其放在网格上。当我按下按钮时,什么也没发生 我的代码随附:Can';t向python Tkinter添加标签,python,tkinter,Python,Tkinter,当我按下python表单上的按钮时,我想添加新标签并将其放在网格上。当我按下按钮时,什么也没发生 我的代码随附: from Tkinter import * class Application(Frame): def __init__(self,master): Frame.__init__(self,master) self.grid() self.create_widgets() def create_widgets(se
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()
创建时应将实际函数传递给
按钮
e、 g
代码中有几个问题: 您在
命令
参数中引用了错误的方法名称,应该是:
searchbtn=按钮(self,text='Search Videos',command=self.Search)
另外,您还有一些属性问题:
您无法访问在此方法之外的create\u widget
方法中定义的topictxt
,除非将其设置为实例属性,方法如下:
self.topiclbl=Label(self,text='输入搜索主题',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()
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()