Reputation: 955
I am new to coding and trying to figure this out and I cannot, and I can't seem to find any videos on youtube that shows this either.
Essentially what i want to do is have a loop running, and be able to click a button and it change a variable in the loop. For instance:
from tkinter import *
import time
root = Tk()
x = 0
def changeVariable():
x = x + 5
button1 = Button(root, text="add 5", command=changeVariable)
button1.pack()
while True:
root.mainloop()
while x > 0:
print("X is greater than 0")
x = x - 1
time.sleep(1)
else:
print("Please click the button")
time.sleep(1)
I have tried all sorts of things and i cannot get the button to change the value of X in my while loop. Can someone please explain how to do this or link a video/guide that does a good job explaining this to a novice?
Thanks
Upvotes: 1
Views: 136
Reputation: 546
You cannot put code after the mainloop. You do not need root.mainloop
as there is a forever loop already in your code. You can just remove root.mainloop
and your code should work.
Edit: Another issue is that x is not defined globally. At the beginning of the changeVariable
function, add the code global x
.
The final issue is that you use time.sleep()
. You don't want to use a time.sleep
as the button could be pressed while everything is frozen. See edit 2 for a fix.
Edit 2:
You can use the tkinter after
method. The after
method can be applied to any tkinter object. In this case, we will apply it to root. This is the basic syntax: root.after(milliseconds, function_to_execute_after_wait)
. The function to execute is optional. In your case, instead of time.sleep(1)
, you should use root.after(1000)
. Make sure to add a root.update()
after your root.after(1000)
.
You can also use +=
or -=
for changing variables. Instead of x = x + 5
, you can use x += 5
. Instead of x = x - 1
, you can use x -= 1
.
Final Code:
from tkinter import *
root = Tk()
x = 0
def changeVariable():
global x
x += 5
button1 = Button(root, text="add 5", command=changeVariable)
button1.pack()
while True:
while x > 0:
print("X is greater than 0")
x -= 1
root.after(1000)
root.update()
else:
print("Please click the button")
root.after(1000)
root.update()
Upvotes: 1