Home > Back-end >  How to make python program wait for a variable to change in tkinter?
How to make python program wait for a variable to change in tkinter?

Time:02-02

I'm trying to understand the functionality of .wait_variable() method. How does it actually work? Because it doesn't work the way I wanted it to.

Here is the try-out I've done:

import tkinter as tk

def func1():
    print(1)
    root.wait_variable(var)
    print(2)

def func2():
    print(3)
    global var
    var = True
    print(4)
    
root = tk.Tk()

var = False
button1 = tk.Button(root, text="Button 1", command=func1)
button1.pack()
button2 = tk.Button(root, text="Button 2", command=func2)
button2.pack()

root.mainloop()

Here's the output when I press the Button 1 and Button 2 in order:

1
3
4

Intended Output:

1
3
4
2

How can I achieve this?

CodePudding user response:

As explained by @Thingamabobs, the wait_variableexpect the variable to be a tkinter.BooleanVar, a tkinter.IntVar, a tkinter.DoubleVar or a tkinter.StringVar. As a result, the corrected code would be:

import tkinter as tk


def func1():
    print(1)
    root.wait_variable(var)
    print(2)


def func2():
    print(3)
    global var  # not required
    var.set(True)
    print(4)


root = tk.Tk()

var = tk.BooleanVar()
button1 = tk.Button(root, text="Button 1", command=func1)
button1.pack()
button2 = tk.Button(root, text="Button 2", command=func2)
button2.pack()

root.mainloop()

Then, when you press the Button 1 and Button 2 in order, the output is then

1
3
4
2
  • Related