2015-07-20 57 views
0

我的計數器不會停止。當我第二次啓動時,我希望它繼續計數,而不是重新啓動。Tkinter程序的行爲不像我認爲的那樣

from tkinter import * 

master = Tk() 

Counter_Activation_Variable=3 

def start(): 
    Counts=0 
    Counter_Activation_Variable=0 
    button.configure(text = "Stop", command=stop) 
    while Counter_Activation_Variable == 0: 
     Counts = Counts+1 
     Textbox.delete(1.0, END) 
     Textbox.insert(END,(Counts)) 
    master.update() 

def stop(): 
    Counter_Activation_Variable=5 
    button.configure(text = "Start", command=start) 
    master.update() 

button = Button(master, text="Start",command=start, bg="grey") 
button.pack(side='bottom', fill='none', expand=False, padx=4, pady=4) 
master.title("Stopwatch") 

Textbox = Text(master, height=1, width=175) 
Textbox.pack(side='top', fill='none', expand=False, padx=4, pady=4) 

master.mainloop() 
+1

描述性變量和方法名稱真的會在這種情況下有所幫助:) –

+0

你是什麼意思對不起,如果它明顯,但即時通訊新編碼大部分這個我只是從其他網站一起凝結和理解 – PLP123

+3

我可以弄清楚你的代碼函數,但使用諸如「timer_status」而不是「a」或「seconds」而不是「x」的描述性變量名稱,確實使編程變得光榮。這是一個很好的提示,因爲你是新的:) –

回答

1

這裏有兩個問題。更大,更明顯的一個是範圍的問題。

簡單的答案是,你只需要兩條額外的線來解決這個問題。

def start(): 
global Counter_Activation_Variable # add this 
Counts=0 
... 
def stop(): 
global Counter_Activation_Variable # and this 
Counter_Activation_Variable = 5 

如果你不這樣做,可變Counter_Activation_Variablestart()方法是指在不同的變量,恰巧也有名字Counter_Activation_Variablestop()方法,它是由一個完全獨立的內部第三個變量在全球範圍內也被命名爲Counter_Activation_Variable

這是因爲Python允許您僅在特定區域(稱爲範圍)中引用變量。因此,函數中定義的變量只存在於該函數內。如果要寫入全局變量,則必須將其明確標記爲全局變量。 (Python可以直接從全局變量中讀取,而不必先聲明它在函數內部)

第二個函數,我之前提到的是線程問題。我在考慮start()中的while循環將佔用所有的計算時間,因此,即使再次單擊該按鈕時,stop()方法可能無法正確執行。

但是,我對TKinter知之甚少,不知道它是否爲您處理那種GUI多線程 - 它可以。

+0

非常感謝你像夢一樣工作 – PLP123

+0

我還使用了'Counts'的全局開始恢復,而不是重新啓動計數器 – PLP123

相關問題