2016-11-29 100 views
0

当我点击其他地方时,我的tkinter gui开始冻结。有没有办法阻止?如何防止tkinter冻结,当我点击其他地方?

这里是我的代码:

#========================= 
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() 

注:显示的标签是按钮本身,所以我将其命名为“标签”。

+0

你为什么使用'time.sleep'和'root.after'?另外,除了引用它,并且期望它等于一个整数(它永远不会),你从来不会对'random'模块做任何事情。 – TigerhawkT3

+0

当我删除时间模块时,即使root.after设置为5000,它也会立即开始循环。这不是我想要的。我使用随机模块随机化显示。请参阅r = random.randint(1,3),然后使用sentence = display(r)。 –

+0

哦,现在我看到你在用'random'做些什么。但是,您立即在递归调用中使用它,然后通过'after'调用该函数_again_。所以,你有一个有用的数字,你在有问题的'sleep'之后递归地发送,然后通过适当的'after'发送一个无用的值。这是不好的。 – TigerhawkT3

回答

3

你正在做一些奇怪的事情在你的代码:

  • 在Tkinter的应用
  • 调用按钮的标签使用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()