pythontkinterpause

Is there a simple way to wait for an event to happen?


Alright, so all I want is to wait for a function to be run and then continue the rest of the code. Basically, all I want to do is wait until the user presses a Tkinter button, and then after that start the rest of the code.

from tkinter import *

def function():
    [insert something here]



root=Tk()
btn1=Button(root, command=function)

Now wait until the user presses the button and then continue

print("Yay you pressed a button!")

Solution

  • If you want to continue some code after pressing button then put this code inside function()

    import tkinter as tk  # PEP8: `import *` is not preferred
    
    # --- functions ---
    
    def function():
        print("Yay you pressed a button!")
        # ... continued code ...
        
    # --- main ---
    
    root = tk.Tk()
    
    btn1 = tk.Button(root, command=function)
    btn1.pack()  # put button in window
    
    root.mainloop()   # run event loop which will execute function when you press button
    

    PEP 8 -- Style Guide for Python Code


    EDIT:

    GUIs don't work like input() which waits for user data. Button doesn't wait for user's click but it only inform mainloop what it has to display in window. And mainloop runs loop which gets key/mouse events from system and it checks which Button was clicked and it runs assigned function. GUI can't stops code and wait for button because it would stop also other widgets in window and it would look like it frozen.

    The same is in other GUIs - ie. PyQt, wxPython, Kivy - and other languages - ie. Java, JavaScript.