当我点击其他地方时,我的tkinter gui开始冻结。有没有办法防止这种情况?
这是我的代码:
#=========================
from tkinter import *
from time import sleep
import random
#=====================
root=Tk()
root.title("Wise Words")
root.geometry("500x180+360+30")
root.resizable(0,0)
root.call("wm", "attributes", ".", "-topmost", "1")
#===================
def display(random):
if random == 1:
return "Be wise today so you don't cry tomorrow"
elif random == 2:
return "Frustration is the result of failed expectations"
elif random == 3:
return "Wishes are possibilities. Dare to make a wish"
if True:
sleep(4)
r=random.randint(1,3)
sentence=display(r)
label.configure(text=str(sentence))
label.update_idletasks()
root.after(5000, display(random))
#==================
def Click(event):
display(random)
#======================
label=Button(root, fg="white", bg="blue", text="Click to start!",
font=("Tahoma", 20, "bold"), width=40, height=4,
wraplength=400)
label.bind("<Button-1>", Click)
label.pack()
#================
root.mainloop()
注意:显示的标签是Button本身,因此我将其命名为“label”。
答案 0 :(得分:3)
你在代码中做了几件奇怪的事情:
time.sleep
Label
Tkinter小部件)command
random
模块并期望它评估为整数if True:
)random
同时引用random
模块和传递的参数after
after
调度自身呼叫的功能,允许您安排多次通话if
结构选择随机字符串,而不是使用random.choice
after
)调度display(random)
调用而不是函数本身这不一定是完整的清单。
以下修复了上述问题。
from tkinter import *
import random
def display():
strings = ("Be wise today so you don't cry tomorrow",
"Frustration is the result of failed expectations",
"Wishes are possibilities. Dare to make a wish")
button.config(text=random.choice(strings))
root.after(5000, display)
def click(event=None):
button.config(command='')
display()
root=Tk()
root.title("Wise Words")
root.geometry("500x180+360+30")
root.resizable(0,0)
root.call("wm", "attributes", ".", "-topmost", "1")
button = Button(root, fg="white", bg="blue", text="Click to start!",
font=("Tahoma", 20, "bold"), width=40, height=4,
wraplength=400, command=click)
button.pack()
root.mainloop()