2017-02-23 80 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