First lets correct your imports.
You do not need to import Tkinter twice and it is preferred you do not use *
.
The best way to import Tkinter is like this:
import tkinter as tk
Then simply use the tk.
prefix for Tkinter widgets.
Now to address your looping issue. Tkinter comes with a cool method called after()
. Keep in mind the after()
method uses a number to represent milliseconds so 1000
is 1 second. So in the below code we are running the check_t
function 1000 times a second. You may wish to change that depending on your needs. We can use this method and a function to check the status of your variables and make the needed changes without affecting the mainloop()
like a while
statement will.
import tkinter as tk
root = tk.Tk()
T = 1
X = 0
def printx():
global X
print(X)
def teez():
global T
T = 0
def teeo():
global T
T = 1
def check_t():
global T, X
if T == 1:
X = 5
root.after(1, check_t)
else:
X = 6
root.after(1, check_t)
button1 = tk.Button(root, text = "Print X", command = printx)
button1.pack()
button2 = tk.Button(root, text = "T = 0", command = teez)
button2.pack()
button2 = tk.Button(root, text = "T = 1", command = teeo)
button2.pack()
check_t()
root.mainloop()
The above code will do exactly what you are trying to do without freezing the mainloop()
. That said I really don't like using lots of global statements and prefer the OOP route. The below code is a reworked version of your code that is in OOP.
import tkinter as tk
class MyApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.t = 1 # changed to lower case name as UPPER case is used for constants
self.x = 0
tk.Button(self, text="Print X", command=self.printx).pack()
tk.Button(self, text="T = 0", command=self.teez).pack()
tk.Button(self, text="T = 1", command=self.teeo).pack()
self.check_t()
def printx(self):
print(self.x)
def teez(self):
self.t = 0
def teeo(self):
self.t = 1
def check_t(self):
if self.t == 1:
self.x = 5
self.after(1, self.check_t)
else:
self.x = 6
self.after(1, self.check_t)
MyApp().mainloop()