Answer the question
In order to leave comments, you need to log in
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()
Answer the question
In order to leave comments, you need to log in
. How can I fix this without allocating a separate thread
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 questionAsk a Question
731 491 924 answers to any question