Home > Software engineering >  Is there a simple way to wait for an event to happen?
Is there a simple way to wait for an event to happen?

Time:08-04

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!")

CodePudding user response:

GUIs don't work like input(). Button doesn't wait for your click - like input() does - but it only inform `mainloop what it has to display in window.

If you want to continue some code after pressing buttont 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

  • Related