2017-02-23 81 views
-1

在tkinter,python中,我試圖爲我的導師制作一個'惡作劇'程序,這樣我就可以展示我在tkinter中學到的東西,但我在使用StringVar()時出錯。 這裏是我的代碼:在messagebox上的StringVar()?

from tkinter import * 
root = Tk() 
root.geometry("1x1") 
secs = StringVar() 
sec = 60 
secs.set("60") 
def add(): 
    global secs 
    global sec 
    sec += 1 
    secs.set(str(sec)); 
    root.after(1000, add) 
add() 
messagebox.showinfo("Self Destruct", "This computer will self destruct in {} seconds".format(str(secs))) 

當我執行這個代碼,我得到正確的消息,但我沒有得到一個自然數,我得到PY_VARO。我應該得到一個數字,從60倒數。 謝謝。

+0

使用stringvar.get()來捕捉STRINGVAR的值()。在你的情況下 - messagebox.showinfo(「Self Destruct」,「這臺計算機將在{}秒內自毀」).format(str(secs.get()))) – Suresh2692

+0

您是否在本網站搜索了與「PY_VAR0」 ? –

回答

1

要從StringVar中獲得一個值,請使用.get()方法,而不是str(...)

"This computer will self destruct in {} seconds".format(secs.get()) 

然而,在你的情況下,存在使用STRINGVAR沒有意義的,因爲該目的是不綁定到任何Tk的對照(您的messagebox.showinfo內容將不動態地改變)。你可以直接使用普通的Python變量。

"This computer will self destruct in {} seconds".format(sec) 

正確使用STRINGVAR的是這樣的:

message = StringVar() 
message.set("This computer will self destruct in 60 seconds") 
Label(textvariable=message).grid() 
# bind the `message` StringVar with a Label. 

... later ... 

message.set("This computer is dead, ha ha") 
# when you change the StringVar, the label's text will be updated automatically. 
+0

不是我在找的東西,而是它最好的選擇。謝謝 :) – Jake