当我按下我的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()
答案 0 :(得分:2)
创建时,您应该将实际功能传递给Button
e.g。
searchbtn = Button(self,text = 'Search Videos',command=self.search)
答案 1 :(得分:1)
代码中的一些问题:
您在command
参数中引用了错误的方法名称,它应该是:
searchbtn = Button(self,text = 'Search Videos',command=self.search)
另外,你有一些属性问题:
您无法访问此方法之外的topictxt
方法中定义的create_widget
,除非您将其作为实例属性,这样:
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()