0

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.

2
  • Do you mean that the code pauses at the end of each iteration and proceeds after pressing F9 in each iteration? Commented Nov 29, 2021 at 14:04
  • yep, exactly that Commented Nov 29, 2021 at 14:16

2 Answers 2

2

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.

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

Comments

0

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()

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.