0

I am trying to make a program that when conditions are met, goes back to the beginning and waits. But instead of waiting for the user to push a button, it continues through the code.

I am using python 3.7.4 and Windows 10. I assume this problem occurs because tkinter doesn't wait for user input in this situation, and instead continues through the code.

My code:

from tkinter import *
from tkinter.ttk import *

def start():
    print("Start")
    # Removes all widgets without destroying root
    for widget in root.winfo_children():
        widget.destroy()

    button_1 = Button(root, text="Begin", command=begin).pack()
    button_2 = Button(root, text="Do something else", command=something).pack()
    # I want the program to wait here for the user to click a button

def begin():
    print("\nDoing stuff")
    if True:
        start()
    print("This should not be printed")

def something():
    pass

root = Tk()
root.geometry("300x300")
btn1 = Button(root, text = "Start", command = start)
btn1.pack()
root.mainloop()

This outputs:

Start

Doing stuff
Start
This should not be printed

I want this to output:

Start

Doing stuff
Start

And then wait for the user to select a button.

1 Answer 1

2

If you want a function to wait for a user action, you need to explicitly tell it to wait.

Tkinter has three functions for that. One is wait_window, which will wait for a window to be destroyed. One is wait_visibility, which will wait for the visibility of a window to change. The third one is wait_variable, which waits for a specific tkinter variable to be set.

While tkinter is waiting, it's able to service other events.

In your case, the solution might look something like this:

var = BooleanVar(value=False)
def do_something():
    something()
    var.set(True)
button_2 = Button(root, text="Do something else", command=do_something).pack()

print("waiting...")
root.wait_variable(var)
print("done waiting.")

When you modify your code to include the above snippet, you'll notice that "waiting..." will be printed on stdout, and then nothing else will be printed until you click on the "Do something else" button and something returns, allowing the variable to be modified.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.