几次随机单击按钮后,我的应用程序开始急剧减速,有时标签和按钮完全消失,GUI冻结(“ X”按钮除外,它只是破坏了程序,这是有意的)。
我的猜测是,我要清除窗口的方式(我的clear(self)函数)不是清除它的正确方法,因为无论您单击哪个按钮,我都希望按钮保持不变,应该清除其下方的所有内容。或者也许是我的类结构,我已经看到了创建tkinter类的许多其他方法...,也许我在代码中缺少了核心内容?
到目前为止,我的代码:
from tkinter import *
class LearnTkinter:
def __init__(self, top):
self.top = top
self.title = top.title("LearnTkinter")
self.configure = top.configure(bg="#d9d9d9", highlightbackground="grey", highlightcolor="darkgrey")
wWidth = top.winfo_reqwidth()
wHeight = top.winfo_reqheight()
x = int(top.winfo_screenwidth() / 2 - (wWidth / 2))
y = int(top.winfo_screenheight() / 3 - (wHeight / 2))
top.geometry(f"+{x}+{y}")
top.minsize(274,520)
self.Kill = Button(top,text="X",bg="#d9d9d9", command = top.destroy).place(height=54,width=72)
self.Infos = Button(top, text="i", bg="#d9d9d9", command=self.info_w).place(relx=0.25,height=54,width=72)
self.Help = Button(top, text="?", bg="#d9d9d9", command=self.help_w).place(relx=0.5,height=54,width=72)
self.Settings = Button(top, text="O", bg="#d9d9d9", command=self.settings_w).place(relx=0.75,height=54,width=72)
self.Frame1 = Frame(top, bg="black", relief="groove", borderwidth="8").place(rely=0.1,relheight=0.202,relwidth=1.004)
def clear(self):
for widget in top.winfo_children():
widget.destroy()
Button(top,text="X", bg="#d9d9d9", command=top.destroy).place(height=54,width=72)
Button(top, text="i", bg="#d9d9d9", command=self.info_w).place(relx=0.25,height=54,width=72)
Button(top, text="?", bg="#d9d9d9", command=self.help_w).place(relx=0.5,height=54,width=72)
Button(top, text="O", bg="#d9d9d9", command=self.settings_w).place(relx=0.75,height=54,width=72)
def info_w(self):
self.clear()
top.title("Info")
Label(top, text="This is going to be the information section ", bg="grey").place(rely=0.1, relwidth=1)
def help_w(self):
self.clear()
top.title("Help")
Label(top, text="This is going to be the help center", bg="grey").place(rely=0.1, relwidth=1)
def settings_w(self):
self.clear()
top.title("Settings")
top = Tk()
exa_gui = LearnTkinter(top)
top.mainloop()
clear
函数中创建4
新按钮。clear
函数后,您创建了5 * 4
新按钮!第二次调用功能按钮时,您创建了5 * 4 * 4
新按钮。这是80
GUI中的新小部件。第四次通话后,您已经有了1280
新按钮!因此,如果您在for loop
(而不是在!期间)之前或之后移动按钮的创建,它将使您的滞后消失:
def clear(self):
for widget in self.top.winfo_children():
widget.destroy()
Button(self.top, text="X", bg="#d9d9d9", command=self.top.destroy).place(height=54,width=72)
Button(self.top, text="i", bg="#d9d9d9", command=self.info_w).place(relx=0.25,height=54,width=72)
Button(self.top, text="?", bg="#d9d9d9", command=self.help_w).place(relx=0.5,height=54,width=72)
Button(self.top, text="O", bg="#d9d9d9", command=self.settings_w).place(relx=0.75,height=54,width=72)
还有一件事:
LearnTkinter
您都引用top
变量。self.top
而是在使用top
。top
在程序中命名了变量。该top
变量:
top = Tk() #You are referring in you 'LearnTkinter' class to this variable. Not the one 'inside' the class.
exa_gui = LearnTkinter(top)
top.mainloop()
我知道在python中您实际上是指向同一个对象。但是,这样做的原因是相同的名称。尝试更改它,您将看到它将无法工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句