I'm trying to create a simple Python GUI (with Tkinter) with start button, running a while loop in a thread, and a stop button to stop the while loop.
I'm having issue with the stop button, which doesn't stop anything and frozen GUI once the start button is clicked.
See code below:
import threading
import Tkinter
class MyJob(threading.Thread):
def __init__(self):
super(MyJob, self).__init__()
self._stop = threading.Event()
def stop(self):
self._stop.set()
def run(self):
while not self._stop.isSet():
print "-"
if __name__ == "__main__":
top = Tkinter.Tk()
myJob = MyJob()
def startCallBack():
myJob.run()
start_button = Tkinter.Button(top,text="start", command=startCallBack)
start_button.pack()
def stopCallBack():
myJob.stop()
stop_button = Tkinter.Button(top,text="stop", command=stopCallBack)
stop_button.pack()
top.mainloop()
Any idea how to solve this? I'm sure this is trivial and must have be done thousands of times but I cannot find a solution myself.
Thanks
David
The code is calling run method directly. It will call the method in the main thread. To run it in a separated thread you should use threading.Thread.start method.
def startCallBack():
myJob.start()
Related
I am trying to get my head around threading in python, I have pieced together a simple tkinter UI that can run a background task to better understand how it all works.
I seem to have got to the point where I can create a seperate thread and interact with the GUI but the problem comes when I try to carry out the task the second time.
I believe what I am missing is a way to tell the daemon when to stop the thread.
Here is my code thus far:
import threading
import tkinter as tk
from collections import deque
from threading import Thread
from random import randint
from time import sleep
class Emitter:
def __init__(self):
self.stop_event = threading.Event()
self.thread = Thread(target=self.emit_text)
self.running = False
def emit_text(self):
sleep(3)
messageQueue.append(f'Random number: {randint(0, 100)}')
# self.thread.set()
def start_emit(self):
ui.consume_text()
self.thread.setDaemon(True)
self.thread.start()
class UI:
def __init__(self):
self.root = tk.Tk()
self.label = tk.Label(self.root, text='Original text')
self.label.pack()
start = tk.Button(self.root, text='Start Download', command=lambda x=Emitter(): x.start_emit())
start.pack()
def consume_text(self):
try:
self.label['text'] = messageQueue.popleft()
except IndexError:
self.root.after(ms=1000, func=self.consume_text)
messageQueue = deque()
ui = UI()
ui.root.mainloop()
I have tried to understand other answers but I can't grasp how you tell the daemon/thread what it's condition to stop is.
The prgram works as intended the first time you click the button, but then if you try to click it again it gives the error RuntimeError: cannot set daemon status of active thread even if I have waited for the Emitter to finish it's task
Thanks to #Solomon Slow for their comment, the problem I had was I was trying to restart the thread but in fact I should have been creating a new one each time.
To fix the problem, I changed my class Emitter class to create a new thread each time start_emit() is called.
The fixed class:
class Emitter:
def __init__(self):
self.stop_event = threading.Event()
def emit_text(self):
sleep(3)
messageQueue.append(f'Random number: {randint(0, 100)}')
def start_emit(self):
ui.consume_text()
thread = Thread(target=self.emit_text)
thread.start()
I also removed the self.thread.setDaemon(True) line.
I have the following problem: I would like to create a GUI with tkinter, that reacts to signals, sent from a socket. For example, I would like to be able to terminate the application, when an end signal is received.
For that purpose I have a function, running in a separate thread, that listens for signals and acts accordingly. However, when I try to destroy the tkinter-GUI, the programm stops, and gives this error message:
Fatal Python error: PyEval_RestoreThread: the function must be called with the GIL held, but the GIL is released (the current Python thread state is NULL)
Python runtime state: initialized
I have recreated this minimum working example giving the same behavior:
import tkinter as tk
import time
import threading
class Gui(tk.Frame):
"""Minimal GUI with only a button"""
def __init__(self, master: tk.Tk):
tk.Frame.__init__(self, master)
self.pack()
tk.Button(self, text='Spam').pack()
class Client:
"""Client for handling signals"""
def __init__(self, master: tk.Tk):
self.master = master
self.gui = Gui(self.master)
self.signal = None # Initialize signal
self.thread = threading.Thread(target=self.listen_thread)
self.running = True
self.thread.start()
def listen_thread(self):
"""Listen for signals and handle actions"""
while self.running:
signal = self.signal # Dummy signal, set by external method, instead of received message from socket
if signal == 'end': # End signal received
self.master.destroy() # Destroy tkinter GUI, error occurs here
self.running = False # Terminate while loop
else:
time.sleep(0.2)
def send_signal_after(receiver: Client, delay: float = 2.0):
"""Send a signal to the client after short delay"""
time.sleep(delay)
receiver.signal = 'end'
if __name__ == '__main__':
root = tk.Tk()
client = Client(root)
threading.Thread(target=send_signal_after, args=(client,)).start()
root.mainloop()
if client.thread: # Check if thread is still running, if so, wait for termination
client.thread.join()
I am running this on MacOS 12.1, Python 3.10.
Is there any other way to terminate the application? I know, I could probably use sys.exit(), but I would like to do this in a cleaner way.
Thank you!
So, to understand how to do it, I made an example:
This is the first file (the main one) :
import tkinter as tk
from tkinter import *
import threading
import file2 as file2
def func(gui):
# just some code around here
# start up the program
root = Tk()
# pass the root in the __init__ function from file2
mainGui = file2.file2Class(root)
# Start the new thread
theThread = threading.Thread(target=func, args=([mainGui]))
theThread.daemon = True
theThread.start()
# loop command
tk.mainloop()
And this is file2 :
import tkinter as tk
from tkinter import *
class file2Class:
root = None
def __init__(self, initialRoot):
self.root = initialRoot
self.createUI();
def createUI(self):
# This is an exit button
tk.Button(
self.root,
text="Exit",
font = "Verdana 10 bold",
fg="red",
command=self.root.destroy, # <- this is the exit command
width=25,
height=2).grid(row=0,column=0)
So, the most important thing is to make sure that you pass root in the args of the thread.
I hope I helped you!
So I have a window which is controlled by a thread that runs in the background and changes the GUI when necessary, at some point this thread will be instructed to change window (involving destroying the window it is in and starting up another window), but this never happens because the thread won't stop executing until the window is changed.
Below is a simplified example:
class Window1:
def __init__(...):
self.Master = tk.Tk()
# some code
self.BackgroundUpdates = threading.Thread(target=self.ActiveWindow)
self.BackgroundUpdates.start()
def ActiveWindow(self):
# gets some instruction
if instruction == 'next window':
nextWindow(self)
def StartWindow(self):
self.Master.mainloop()
def KillWindow(self):
self.Master.destroy()
class Window2:
def __init__(...):
self.Master = tk.Tk()
# some code...
def StartWindow(self):
self.Master.mainloop()
def nextWindow(objectWindow):
objectWindow.KillWindow()
# when this function is called it never gets past the line above
nextWindow = Window2()
nextWindow.StartWindow()
application = Window1()
application.StartWindow()
Is there a way that I could rearrange the way I handle the thread so that I don't run into this problem?
a runnable example:
import tkinter as tk
import threading
class MainWindow:
def __init__(self):
self.Master = tk.Tk()
self.Frame = tk.Frame(self.Master, width=100, height=100)
self.Frame.pack()
self.Updates = threading.Thread(target=self.BackgroundUpdates)
self.Updates.start()
def BackgroundUpdates(self):
# imagine instructions to be a really long list with each element being a
# different instruction
instructions = ['instruction1', 'instruction2', 'next window']
while True:
if instructions[0] == 'next window':
ChangeWindow(self)
else:
instructions.remove(instructions[0])
def StartWindow(self):
self.Master.mainloop()
def KillWindow(self):
self.Master.destroy()
class SecondaryWindow:
def __init__(self):
self.Master = tk.Tk()
self.Frame = tk.Frame(self.Master, width=100, height=100)
self.Frame.pack()
def StartWindow(self):
self.Master.mainloop()
def KillWindow(self):
self.Master.destroy()
def ChangeWindow(oldObject):
oldObject.KillWindow()
# the line above will halt the program, since it has to wait on the thread to
# finish before the window can be destroyed, but this function is being called
# from within the thread and so the thread will never stop executing
del oldObject
newObject = SecondaryWindow()
newObject.StartWindow()
window = MainWindow()
window.StartWindow()
I realised that tkinter is singularly threaded, it can be explained more here:
https://stackoverflow.com/a/45803955/11702354
The problem was that I was trying to destroy my window from a different thread to the one it was created in. To solve this problem I had to use the 'after' method from the Tkinter module as well as using a event, this meant that I could control the background stuff (i.e. wait on a specific command from my connected server) and when I needed to change the window I would set the event.
Part of my adapted code can be seen below:
def CheckEvent(self):
if LOBBY_EVENT.is_set():
ChangeWindow(self, 'game')
self.Master.after(5000, self.CheckEvent)
def StartWindow(self):
self.Master.after(5000, self.CheckEvent)
self.Master.after(2000, self.HandleInstruction)
self.Master.mainloop()
So whenever I was calling the StartWindow method for my window, it would check whether the event has been set every 5 seconds, and then every 2 seconds it would go to a separate function 'HandleInstruction' which allowed me to create a response in my GUI (I also used queues to pass information to this function)
I hope this clears up confusion if anyone is to stumble across it!
I want to create a GUI in tkinter that not only executes commands when a button is pressed, but responds to the state of a larger script running in a separate thread.
I have really dug around and tried to find some information on message passing, and I have found some great info on the pickle module, using multiprocessing and its built in tools and also threading, and queuing. I have even dug into David Beazley's lesson on concurrency located here. I just can't get the syntax right on any of those methods.
I have broken down my code into a small functional unit that should launch a little tkinter window like this:
tkinter window
The code below has a "launchGUI" function that launches my tkinter GUI, a "myLoop" function that starts the threads and will also loop to drive my larger program later, right now it just rotates the blink variable. I also have a blinkCheck method in my class that checks the status of the blink variable in the class.
I don't know if I am even putting my message receiver in the right place. In the following example code I am just trying to pass a global variable into the class. I know it is getting into the class, because the blinkCheck() method works even though uncommenting that method crashes the window. However, with the method turned off the label in the GUI never changes. I think the window crashing is the least of my worries, it must be because i have another while loop running.
What is the correct way to get that number in Label to change?
Here is my example code:
import tkinter as tk
from tkinter import Frame, Label
import time
import threading
blink = 0
class MyClass(tk.Frame):
def __init__(self, master):
self.master = master
super().__init__(self.master)
global blink
self.label = Label(master, text=blink)
self.label.pack()
#self.blinkCheck()
def blinkCheck(self):
global blink
while True:
print("blink in blinkCheck method is = {}".format(blink))
time.sleep(2.5)
def launchGUI():
root = tk.Tk()
root.title("My Blinker")
app1 = MyClass(root)
app1.mainloop()
def myLoop():
global blink
t1=threading.Thread(target=launchGUI)
t1.daemon = True
t1.start()
print("blink in blinker function is {}".format(blink))
while True:
if blink == 0:
blink = 1
else:
if blink == 1:
blink = 0
time.sleep(2.5)
if __name__=="__main__":
myLoop()
In your description you have mentioned something about involving buttons. I do not see that in your provided snippet. But with buttons it is possible to configure the label, i.e:
from tkinter import Label, Button
blink = 0
class MyClass(tk.Frame):
def __init__(self, master):
self.master = master
super().__init__(self.master)
global blink
self.label = Label(master, text=blink)
self.button = Button(master, text="Button", command=lambda: foo(self.label))
self.label.pack()
self.button.pack()
#self.blinkCheck()
def blinkCheck(self):
global blink
while True:
print("blink in blinkCheck method is = {}".format(blink))
time.sleep(2.5)
def foo(self, label):
label.config(text=blink)
Conventionally, this would be the most simple way to configure a label within an active thread.
If anyone feels like this answer may not be fully correct, please do edit it because I am new to Stack Overflow!
First, the GUI must run in main thread, and must not blocked by a infinite loop. Use after instead. To communicate, use some appropriate object from threading, e.g. Event:
import tkinter as tk
import time
import threading
class MyClass(tk.Frame):
def __init__(self, master, event):
super().__init__(master)
self.master = master
self.event = event
self.label = tk.Label(master, text='')
self.label.pack()
self.after(100, self.blink_check)
def blink_check(self):
self.label['text'] = self.event.is_set()
self.after(100, self.blink_check)
def blink(event):
while True:
event.set()
time.sleep(2.5)
event.clear()
time.sleep(2.5)
def main():
root = tk.Tk()
root.title("My Blinker")
event = threading.Event()
t = threading.Thread(target=blink, args=(event,))
t.daemon = True
t.start()
frame = MyClass(root, event)
root.mainloop()
if __name__=="__main__":
main()
This question already has answers here:
Tkinter: How to use threads to preventing main event loop from "freezing"
(5 answers)
Closed 4 years ago.
I wanted to create a non-blocking message window with Tkinter. This in order to display a wait message, when another function is waiting for a reply. Once the reply is received the window can be closed automatically. I managed to find some info on the web and I made the following:
import tkinter as tk
import threading
import time
class Show_Azure_Message(threading.Thread):
def __init__(self, message):
self.thread = threading.Thread.__init__(self)
self.message = message
self.start()
#staticmethod
def callback():
return
def destroy(self):
self.root.quit()
#run will be called from self.start()
def run(self):
self.root = tk.Tk()
self.root.protocol("WM_DELETE_WINDOW", self.callback)
self.t2 = tk.Text(self.root, height=10, borderwidth=0, wrap=tk.WORD)
self.t2.insert(1.0, self.message)
self.t2.grid(padx=5,row=2)
self.t2.config(state=tk.DISABLED)
self.root.mainloop()
App = Show_Azure_Message('Hello')
for i in range(0,2):
print(i)
time.sleep(1)
App.destroy()
This runs fine when I execute this as main script, but when I want to run another gui application with Tkinter right after i get the following error
RuntimeError: main thread is not in main loop
Also when I run another piece of code after the App.destroy(). Then the App window doesn't close end the application keeps running.
root = tk.Tk()
label = tk.Label(root, text='Hello2')
label.pack()
root.mainloop()
So probably I am doing something wrong but I cannot find out what the problem is. Next to that I don't have much experience with Python Threads hence maybe I am missing something trivial over here.
regards,
Geert
I think, if you really want to do it that way (look in the comment section of your post) you should use a Toplevel window instead since they don't need a mainloop which is making things way more easy in my eyes.
That's some kind of how I would do it if I would have to:
from tkinter import *
import threading
import time
class Show_Azure_Message(Toplevel):
def __init__(self,master,message):
Toplevel.__init__(self,master) #master have to be Toplevel, Tk or subclass of Tk/Toplevel
self.title('')
self.attributes('WM_DELETE_WINDOW',self.callback)
self.resizable(False,False)
Label(self,text=message,font='-size 25').pack(fill=BOTH,expand=True)
self.geometry('250x50+%i+%i'%((self.winfo_screenwidth()-250)//2,(self.winfo_screenheight()-50)//2))
def callback(self): pass
BasicApp=Tk()
App = Show_Azure_Message(BasicApp,'Hello')
for i in range(0,2):
print(i)
time.sleep(1)
App.destroy()