消息框上的 StringVar()?
StringVar() on messagebox?
在 tkinter 中,python,我正在尝试为我的导师制作一个 'prank' 程序,这样我就可以展示我在 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 开始倒数。
谢谢
要从 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.
在 tkinter 中,python,我正在尝试为我的导师制作一个 'prank' 程序,这样我就可以展示我在 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 开始倒数。
谢谢
要从 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.