messagebox上的StringVar()?

2024-04-26 06:46:56 发布

您现在位置:Python中文网/ 问答频道 /正文

在python的tkinter中,我试图为我的导师制作一个“恶作剧”程序,以便展示我在tkinter中所学的知识,但我在使用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开始倒数。 谢谢。在


Tags: 代码程序addtkinter数字rootsecglobal
1条回答
网友
1楼 · 发布于 2024-04-26 06:46:56

要从StringVar获取值,请使用.get()方法,而不是str(...)。在

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

但是,在您的例子中,使用StringVar没有任何意义,因为这个对象没有绑定到任何Tk控件(您的messagebox.showinfo内容将而不是被动态更改)。您也可以直接使用纯Python变量。在

^{pr2}$

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.

相关问题 更多 >