K
K
Kostayn_junior2021-06-08 13:27:29
Python
Kostayn_junior, 2021-06-08 13:27:29

How to handle button click while loop is running?

I have a program with two buttons written in tkinter (python). One of them starts the loop, the condition of which is the flag, and the second changes the value of the flag, on which the loop should be interrupted. But when you start the loop and try to press the button to change the flag, the program stops responding. How can this be fixed without dedicating a separate thread to the application?
Here is my application code

from tkinter import *

root = Tk()
root.title('Test')
root.geometry('350x200')
root.resizable(width=False, height=False)
i = 1
check = 0
def btnInterrupt_click():
    global check
    check = 1
def test():
    while check == 0:
        global i
        i += 1
        print(check)
btnStart = Button(root, text='Start', fg='black', bg='white', width=8, command=test)
btnStart.pack()
btnInterrupt = Button(root, text='Прервать', fg='black', bg='white', width=8, command=btnInterrupt_click)
btnInterrupt.pack()

root.mainloop()

60bf4607804f0494310020.png

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Ronald McDonald, 2021-06-08
@Zoominger

. How can I fix this without allocating a separate thread

No way. Your program is running in a single GUI thread, which is why it hangs.
Usually the program is divided into GUI and handlers in different threads just so that it does not hang.

D
Daniil Shevkunov, 2021-06-08
@danila763

Write asynchronous code

O
o5a, 2021-06-08
@o5a

You don't need to use your own loops so as not to conflict with the tkinter loop. To start by time, there is root.after (time in ms, function), you can also loop through it.

def something():
    if check != 0:
        # какие-то вычисления
        root.after(1000, something)

# для запуска самого цикла из основного кода программы
root.after(0, something)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question