Home > Blockchain >  Python tkinter: pausing a loop until key pressed
Python tkinter: pausing a loop until key pressed

Time:11-29

I am working on a piece of code with tkinter like following:

def function_call():
    x = 5;
    for _ in range (10):
        ...
        ...
        ...
        //pause here until F9 is pressed
        


root = tk.Tk()
...
...
...
root.bind('<F1>', lambda event: function_call()) //Using F1 to invoke call

Does anyone know how to pause the loop, until F9 is pressed? Please help.

CodePudding user response:

tkinter has a function .wait_variable(var) to pause the application and wait for tkinter var to be updated. So you can bind key <F9> to update the tkinter variable to stop the waiting:

import tkinter as tk

def function_call(event=None):
    for i in range(10):
        print('Hello', i)
        # wait for pause_var to be updated
        root.wait_variable(pause_var)
    print('done')

root = tk.Tk()
# tkinter variable for .wait_variable()
pause_var = tk.StringVar()
root.bind('<F1>', function_call)
# press <F9> to update the tkinter variable
root.bind('<F9>', lambda e: pause_var.set(1))
root.mainloop()

Note that if the job inside the for loop is time-consuming, then better to run function_call() in a child thread instead.

CodePudding user response:

Here is some code you can build on. It will wait until "F9" key is pressed, and when pressed it will change text.

import tkinter as tk
from tkinter import Label

root = tk.Tk()
root.geometry("300x300")

state = 'startup'


def loop():
    if state == 'startup':
        Label(text="The Game is starting now!").grid(row=0, column=0)
    elif state == 'running':
        Label(text="The Game is running now!").grid(row=0, column=0)

    root.after(20, loop)


def key(event):
    global state
    if state == 'startup':
        state = 'running'


root.bind('<Key-F9>', key)
root.after(20, loop)
root.mainloop()
  • Related