In tkinter, python, I'm trying to make a 'prank' program for my tutor so I can show what I've learnt in tkinter, yet I'm having an error using StringVar()
.
Here's my code:
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)))
When I execute this code I get the correct message yet I do not get a counting number, I get PY_VARO
. I should be getting a number, counting down from 60.
Thanks.
To get a value out of a StringVar, use the .get()
method, instead of str(...)
.
"This computer will self destruct in {} seconds".format(secs.get())
However, in your case there is no point using a StringVar, since this object is not bound to any Tk controls (your messagebox.showinfo
content will not be changed dynamically). You could as well just use a plain Python variable directly.
"This computer will self destruct in {} seconds".format(sec)
A proper use of StringVar looks like this:
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.