Passing variables into a tkinter class window - python

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

Related

How can I terminate a tkinter mainloop from a different thread

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!

Thread won't stop until window is destroyed, window won't destroy unless thread is stopped

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!

Tkinter exit command with infinite loop

I'm having some issue with the close button of the interface window with tkinter. My tool displays some video in real time, I do that with an infinite loop with the after function.
When I close the tkinter window by clicking on the cross, the program freezes. However, when I click on the button, the same function is called but it closes properly.
Here is the most simplified code I came up to show you the problem. Does anyone have an explanation and a way to solve it?
(BTW, I'm using Python 2.7.8 on OSX)
from Tkinter import *
from PIL import Image, ImageTk
import numpy as np
class Test():
def __init__(self, master):
self.parent = master
self.frame = Frame(self.parent)
self.frame.pack(fill=BOTH, expand=1)
self.mainPanel = Label(self.frame)
self.mainPanel.pack(fill=BOTH, expand=1)
self.closeButton = Button(self.frame, command=self.closeApp)
self.closeButton.pack(fill=BOTH, expand=1)
def closeApp(self):
print "OVER"
self.parent.destroy()
def task(tool):
print 'ok'
im = Image.fromarray(np.zeros((500, 500, 3)), 'RGB')
tool.tkim = ImageTk.PhotoImage(im)
tool.mainPanel['image'] = tool.tkim
root.after(1, task, tool)
def on_closing():
print "OVER"
root.destroy()
root = Tk()
root.wm_protocol("WM_DELETE_WINDOW", on_closing)
tool = Test(root)
root.after(1, task, tool)
root.mainloop()
Now if you try again with a smaller image (say 100*100), it works. Or if you put a delay of 100 in the after function, it also works. But in my application, I need a really short delay time as I'm displaying a video and my image size is 900px*500px.
Thanks!
Edit (08/19) : I have not found the solution yet. But I may use root.overrideredirect(1) to remove the close button and then recreate it in Tk, and also add drag a window using : Python/Tkinter: Mouse drag a window without borders, eg. overridedirect(1)
Edit (08/20) : Actually, I can not even drag the window. The tool is also freezing!
You probably just need to kill your animation loop. after returns a job id which can be used to cancel pending jobs.
def task():
global job_id
...
job_id = root.after(1, task, tool)
def on_closing():
global job_id
...
root.after_cancel(job_id)
Your code could be a bit cleaner if these functions were methods of the object so you didn't have to use a global variable. Also, you should have one quit function rather than two. Or, have one call the other so you are certain both go through exactly the same code path.
Finally, you shouldn't be calling a function 1000 times a second unless you really need to. Calling it so often will make your UI sluggish.
I found a solution, I'm not sure it is really clean, but at least it is working for what I want to do. I no longer use after but I loop and update the gui at each iteration.
from Tkinter import *
from PIL import Image, ImageTk
import numpy as np
class Test():
def __init__(self, master):
self.parent = master
self.frame = Frame(self.parent)
self.frame.pack(fill=BOTH, expand=1)
self.mainPanel = Label(self.frame)
self.mainPanel.pack(fill=BOTH, expand=1)
self.parent.wm_protocol("WM_DELETE_WINDOW", self.on_closing)
self.close = 0
def on_closing(self):
print "Over"
self.close = 1
def task(self):
print "ok"
im = Image.fromarray(np.zeros((500, 500, 3)), 'RGB')
self.tkim = ImageTk.PhotoImage(im)
self.mainPanel['image'] = self.tkim
root = Tk()
tool = Test(root)
while(tool.close != 1):
tool.task()
root.update()
root.destroy()

Stopping a python thread from a tkinter gui

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

Python Threading

I'm trying to make a simple program that continually displays and updates a label that displays the CPU usage, while having other unrelated things going on.
I've done enough research to know that threading is likely going to be involved. However, I'm having trouble applying what I've seen in simple examples of threading to what I'm trying to do.
What I currently have going:
import Tkinter
import psutil,time
from PIL import Image, ImageTk
class simpleapp_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
self.labelVariable = Tkinter.StringVar()
self.label = Tkinter.Label(self,textvariable=self.labelVariable)
self.label.pack()
self.button = Tkinter.Button(self,text='button',command=self.A)
self.button.pack()
def A (self):
G = str(round(psutil.cpu_percent(), 1)) + '%'
print G
self.labelVariable.set(G)
def B (self):
print "hello"
if __name__ == "__main__":
app = simpleapp_tk(None)
app.mainloop()
In the above code I'm basically trying to get command A continually running, while allowing command B to be done when the users presses the button.
You should never attempt to alter a UI element from a thread that isn't the main thread.
What you probably want is after(delay_ms, callback, args). Some information can be over at http://www.pythonware.com/library/tkinter/introduction/x9507-alarm-handlers-and-other.htm.
As a sample, here's a quick script to show a clock (Note: I've never really used Tk).
from Tkinter import *
from time import strftime
class App(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.label_var = StringVar()
self.label = Label(self, textvariable=self.label_var)
self.label.pack()
# Start the loop
self.go()
def go(self):
self.label_var.set(strftime("%H:%M:%S"))
# The callback is only called once, so call it every time
self.after(1000, self.go)
app = App()
mainloop()
You don't need threads for such a simple task. You can simply schedule your task to run every second or so, which can be done with the 'after' method;
First, add this method to your simpleapp_tk class:
def update(self):
G = str(round(psutil.cpu_percent(), 1)) + '%'
self.labelVariable.set(G)
self.after(1000, self.update)
Then, in your initialize method add this call:
self.update()
This will cause the label to be updated to the current cpu value. The update method will then re-schedule itself to run again in one second.

Categories