在Minimal App from the Tkinter Docs的基础上,我添加了一个按钮按下时调用的函数。函数只是在窗口中显示一个标签。当我第二次按下按钮时,我希望它删除旧标签并显示新标签。相反,grid_forget()
并没有删除标签,它只是在新行上重复标签。你知道吗
为什么标签小部件没有从窗口中删除?下面的代码说明了这个问题。我在这里读到了无数关于从显示中删除小部件和使用grid\u forget()的问题。你知道吗
我唯一能想到的是,小部件可能是displayText()
的局部变量,每次按下按钮调用它时,都不存在display
变量,并且引发异常。我试图使display
成为一个全局变量,但没有成功。你知道吗
import Tkinter as tk
def displayText():
try:
display.grid_forget()
display.destroy()
except UnboundLocalError:
#Display will not exist on first button press
pass
label = 'Hello World'
display = tk.Label(text=label)
#Also tried called display.grid_forget() here
display.grid()
display.bell()
class Application(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self,master)
self.grid(sticky=tk.N+tk.E+tk.W)
self.createWidgets()
def createWidgets(self):
top=self.winfo_toplevel()
top.geometry('300x100+50+50')
top.rowconfigure(0, weight=1)
top.columnconfigure(0, weight=1)
self.columnconfigure(0, weight=1)
self.check = tk.Button(self, text='Say Hi', command=lambda : displayText())
self.check.grid(row=0, column=0, sticky=tk.N+tk.E+tk.W)
app = Application()
app.master.title('Test App')
app.mainloop()
您可以将小部件
display
分配给def __init__()
中的主类,并将函数作为方法移动。目标是在应用程序运行期间保持对小部件的控制。你知道吗相关问题 更多 >
编程相关推荐