2016-11-29 99 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()