Separating Tkinters GUI and control of the application - python-3.x

1) What is my goal:
I’m creating an application that should read data every 60s from ModBusServer, append those data to Graphs and then when the app is closed save the data to excel file.
Site note:
The process of reading data from ModBusServer and appending them to graphs should start after a start button is pressed.
And end after stop button is pressed OR when ModBusServer sends a request to stop.
2) What I have so far:
I created the GUI without any major problems as a class “GUI_komora”.
Everything there works just fine.
3) What is the problem:
But now I’m lost on how to approach the “read data every 60 seconds”, and overall how to control the application.
I did some research on threading but still I’m confused how to implement this to my application.
I learned how to make functions run simultaneously in this tutorial.
And also how to call a function every few seconds using this question.
But none of them helped me to learn how to control the overall flow of the application.
If you could redirect me somewhere or tell me about a better approach I would be really glad.
Some of my code:
from tkinter import *
from GUI_komora import GUI
root = Tk()
my_gui = GUI(root) #my GUI class instance
#main loop
root.mainloop()
"""
How do I achieve something like this???
whenToEnd = False
while whenToEnd:
if step == "Inicialzation":
#inicializace the app
if step == "ReadData":
#read data every 60 seconds and append them to graphs
if step == "EndApp"
#save data to excel file and exit app
whenToEnd = True
"""

Here is an example of a loop that takes a decision (every 60 sec in your case) and pushes the outcome of the decision to tkinter GUI: https://github.com/shorisrip/PixelescoPy/blob/master/base.py
Parts:
main thread - starts tkinter window
control thread - reads some data and decides what to show in GUI
GUI class - has a method "add_image" which takes input an image and displays on GUI.(add_data_to_graph maybe in your case). This method is called everytime by the control thread.
Snippets:
def worker(guiObj, thread_dict):
# read some data and make decision here
time.sleep(60)
data_to_show = <outcome of the decision>
while some_logic:
pictureObj = Picture(chosen, timer)
pictureObj.set_control_thread_obj(thread_dict["control_thread"])
guiObj.set_picture_obj(pictureObj)
pictureObj.display(guiObj)
# do post display tasks
guiObj.quit_window()
# Keep GUI on main thread and everything else on thread
guiObj = GuiWindow()
thread_list = []
thread_dict = {}
thread_for_image_control = threading.Thread(target=worker, args=(guiObj,
thread_dict))
thread_dict["control_thread"] = thread_for_image_control
thread_list.append(thread_for_image_control)
thread_for_image_control.start()
guiObj.run_window_on_loop()
# thread_for_image_control.join()
Code for Picture class:
class Picture:
def __init__(self, path, timer):
self.path = path
self.timer = timer
self.control_thread_obj = None
def set_control_thread_obj(self, thread_obj):
self.control_thread_obj = thread_obj
def display(self, guiObj):
image_path = self.path
guiObj.add_image(image_path)
time.sleep(self.timer)
Code for GUI class
class GuiWindow():
def __init__(self):
self.picture_obj = None
self.root = Tk()
self.image_label = None
self.image = None
self.folder_path = None
self.timer = None
self.root.protocol("WM_DELETE_WINDOW", self.exit_button)
def add_image(self, image_path):
resized_img = self.resize(image_path)
image_obj = ImageTk.PhotoImage(resized_img)
image_label = Label(self.root, image=image_obj,
height=resized_img.height,
width=resized_img.width)
self.image = image_obj # DO NOT REMOVE - Garbage collector error
if self.image_label is not None:
self.remove_image()
image_label.grid(row=0, column=0, columnspan=3)
self.image_label = image_label
Here based on my control loop thread I am changing image (in your case graph data) of the tkinter GUI.
Does this help?

Related

Tkinter window freezes / lags whenever the user inputs text to text field

I am currently working on a server / client chat program which works fine on terminal but in trying to migrate it into a windowed program I've come across a few errors which I have managed to solve except for this one, for whatever reason, in the GUI class running on the main thread seems to lag considerably whenever the user focuses their attention on it or whenever they try to interact with it, I've tried to use threading but I'm not sure what the problem is.
...
class GUI():
def __init__(self):
self.txtval = []
self.nochngtxtval = []
self.root = tk.Tk()
self.root.title("Chatroom")
self.root.geometry("400x200")
self.labl = tk.Label(self.root, text="", justify=tk.LEFT, anchor='nw', width=45, relief=tk.RIDGE, height=8)
self.labl.pack()
count = 1
while events["connected"] == False:
if events["FError"] == True:
quit()
self.labl["text"] = "Loading"+"."*count
count += 1
if count > 3:
count = 1
self.labl["text"] = ""
self.inputtxt = tk.Text(self.root,height=1,width=40,undo=True)
self.inputtxt.bind("<Return>", self.sendinput)
self.sendButton = tk.Button(self.root, text="Send")
self.sendButton.bind("<Button-1>", self.sendinput)
self.sendButton.pack(padx=5,pady=5,side=tk.BOTTOM)
self.inputtxt.pack(padx=5,pady=5,side=tk.BOTTOM)
uc = Thread(target=self.updatechat,daemon=True)
uc.start()
self.root.protocol("WM_DELETE_WINDOW", cleanAndClose)
self.root.mainloop()
def updatechat(self):
global events
while True:
if events["recv"] != None:
try:
current = events["recv"]
events["recv"] = None
... # shorten to reasonable length (45 characters)
self.labl['text'] = ''
self.txtval = []
self.nochngtxtval.append(new+"\n")
for i in range(len(nochngtxtval)):
self.txtval.append(nochngtxtval[i])
self.txtval.pop(len(self.txtval)-1) # probably not necessary
self.txtval.append(new+"\n") # probably not necessary
self.txtval[len(self.txtval)-1] = self.txtval[len(self.txtval)-1][:-1]
for i in range(len(self.txtval)):
self.labl['text'] = self.labl['text']+self.txtval[i]
except Exception as e:
events["Error"] = str(e)
pass
def sendinput(self, event):
global events
inp = self.inputtxt.get("1.0", "end").strip()
events["send"] = inp
self.inputtxt.delete('1.0', "end")
... # start the logger and server threads
GUI()
I'm using my custom encryption which is linked on github https://github.com/Nidhogg-Wyrmborn/BBR
my server is named server.py in the same git repo as my encryption.
EDIT:
I added a test file which is called WindowClasses.py to my git repo which has no socket interactions and works fine, however the problem seems to be introduced the moment i use socket as displayed in the Client GUI. I hope this can help to ascertain the issue.

Python tkinter- Threading through button click

I am displaying a sensor device's measurement values using the Tkinter GUI application. The sensor sends new data every second. I started a new thread and put the result in a Queue and process the queue to display the values on GUI. Now I am facing another problem. The sensor has two modes of operations. For simplicity, I have used a random generator in the program. Users should be able to switch the modes using two buttons. Button-1 for Mode-1, Button-2 for Mode-2. (say the mode-1 operation is random.randrange(0,10) and mode-2 operation is random.randrange(100, 200). How do I control these two operations through Threading? if a user started a mode-1 operation, when he presses the Button-2, the mode-1 operation should stop (thread-1) and mode-2 operation (thread-2) should start. Does it mean do I need to kill thread-1? Or is there any way to control two modes in same thread? I am totally new into threading. Any suggestions, please.
import tkinter
import threading
import queue
import time
import random
class GuiGenerator:
def __init__(self, master, queue):
self.queue = queue
# Set up the GUI
master.geometry('800x480')
self.output = tkinter.StringVar()
output_label = tkinter.Label(master, textvariable= self.output)
output_label.place(x=300, y=200)
#I haven't shown command parts in following buttons. No idea how to use it to witch modes?
mode_1_Button = tkinter.Button(master, text = "Mode-1")
mode_1_Button.place(x=600, y=300)
mode_2_Button = tkinter.Button(master, text = "Mode-2")
mode_2_Button.place(x=600, y=400)
def processQueue(self):
while self.queue.qsize():
try:
sensorOutput = self.queue.get() #Q value
self.output.set(sensorOutput) #Display Q value on GUI
except queue.Empty:
pass
class ClientClass:
def __init__(self, master):
self.master = master
# Create the queue
self.queue = queue.Queue()
# Set up the GUI part
self.myGui = GuiGenerator(master, self.queue)
#How do I switch the modes of operations? do I need some flags setting through button press?
# Set up the thread to do asynchronous I/O
self.thread1_mode1 = threading.Thread(target=self.firstModeOperation)
self.thread1_mode1.start()
# Start the periodic call in the GUI to check if the queue contains
# anything new
self.periodicCall()
def periodicCall(self):
# Check every 1000 ms if there is something new in the queue.
self.myGui.processQueue()
self.master.after(1000, self.periodicCall)
def firstModeOperation(self):
while True: #??? how do i control here through mode selection
time.sleep(1.0)
msg_mode_1= random.randrange(0,10)
self.queue.put(msg_mode_1)
def secondModeOperation(self):
while True: #??? how do i control here through mode selection
time.sleep(1.0)
msg_mode_2= random.randrange(100,200)
self.queue.put(msg_mode_2)
#Operation part
root = tkinter.Tk()
client = ClientClass(root)
root.mainloop()

How to create GUI objects one by one with Tkinter

I like to create an object per second and make the show up one by one. However, the code below wait for 3 seconds and show them all at the same time.
from tkinter import *
import time
def create():
for i in range(3):
r4=Radiobutton(root, text="Option 1"+str(i), value=1)
r4.pack( anchor = W )
time.sleep(1)
root = Tk()
create()
root.mainloop()
Your code, as is, creates a one object per second as you desired it, but this objects need to be shown, and they're shown when code flow reaches the mainloop. Hence, for observer, it looks like there're no objects at all after one second.
Of course, you can use sleep and update, but beware - sleeping leads to unresponsive window, so it's OK option (to be honest - not OK at all), if your application isn't drawn and you're outside of mainloop, but if it's not - prepare for a "frozen" window, because GUI can redraw himself only in mainloop (an event loop, you can reach it with update as well) and sleep blocks this behaviour.
But there's a good alternative, the after method, take a look on it!
And there's a snippet, so you can see the difference:
try:
import tkinter as tk
except ImportError:
import Tkinter as tk
import time
def create_with_sleep():
for _ in range(3):
tk.Radiobutton(frame_for_sleep, text="Sleep Option").pack(anchor='w')
time.sleep(int(time_entry.get()))
root.update()
def create_with_after(times=3):
if times != 0:
tk.Radiobutton(frame_for_after, text="After Option").pack(anchor='w')
times -= 1
root.after(int(time_entry.get()) * 1000, lambda: create_with_after(times))
root = tk.Tk()
test_yard_frame = tk.Frame(root)
frame_for_sleep = tk.Frame(test_yard_frame)
frame_for_after = tk.Frame(test_yard_frame)
test_yard_frame.pack()
frame_for_sleep.pack(side='left')
frame_for_after.pack(side='left')
button_frame = tk.Frame(root)
button_for_sleep = tk.Button(button_frame, text='Create 3 radiobuttons with sleep+update', command=create_with_sleep)
button_for_after = tk.Button(button_frame, text='Create 3 radiobuttons with after', command=create_with_after)
button_frame.pack()
button_for_sleep.pack(side='left')
button_for_after.pack(side='left')
time_label = tk.Label(root, text='Time delay in seconds:')
time_label.pack(fill='x')
time_entry = tk.Entry(root)
time_entry.insert(0, 1)
time_entry.pack(fill='x')
root.mainloop()
With 1 seconds delay there's no much difference, but you can try to increase delay to understand why after option is preferable in general.
You can use update to call a refresh on your objects.
In use, you would have to add the line root.update() in your for loop.

Multithreading in Tkinter

I am new to Python and Tkinter but I was wondering if I could do Multithreading in Tkinter.
I have a Restaurant Simulation program and whenever it accepts an order, this is what should happen:
1) Timer that counts down and shows how many seconds are left before the order is done
2) While the Timer is counting, I want to create another instance of the Restaurant Simulation so that it could accept another order.
This is what I have tried:
from Tkinter import *
class food():
def __init__(self):
self.inventory = []
def cookOrder(self,type):
if type is 'AA': #Cook Barf
self.inventory[0]+=1
class Restaurant():
def Callback(self,root):
if tkMessageBox.askokcancel("Quit", "Do you really wish to quit?"):
root.destroy()
def MainMenu(self):
self.Main = Tk()
self.Main.grid()
Title = Label(self.Main,text = "Welcome to Resto!",font=("Bauhaus 93",20))
Title.grid(columnspan=6)
RestoMenu = Button(self.Main,text = "Order Food",command = lambda:self.Restaurant_Menu('AA'),font=("High Tower Text",12))
RestoMenu.grid(row=2,column=0)
self.Main.mainloop()
def Restaurant_Menu(self,type):
self.Main.destroy()
self.setCookTime(type)
def setCookTime(self,type):
self.MainMenu() #This is not working as I planned it to be
self.cookTimer = Tk()
self.timeLabel = Label(text="")
self.timeLabel.pack()
if type is "AA":
self.Tick(10,type)
self.cookTimer.mainloop()
self.cookTimer.wm_protocol ("WM_DELETE_WINDOW", self.Callback(self.cookTimer)) #Getting TCL Error
def Tick(self,time,type):
time -=1
if time ==-1:
food.cookOrder(type)
self.cook.destroy()
else:
self.timeLabel.configure(text="%d" %time)
self.cookTimer.after(1000, lambda: self.Tick(time,type))
Food = food()
Resto = Restaurant()
Resto.MainMenu()
Now, the problem with the code is, it is not creating another instance of the Restaurant while the countdown is going on. Any help?
Plus, how do you ask the user for the confirmation of exiting program when he clicks the exit button while the timer is ticking, using WM_DELETE_WINDOW?

PyQt: How do I handle QPixmaps from a QThread?

This has to be the biggest nuisance I've encountered with PyQT: I've hacked together a thumbnailing thread for my application (I have to thumbnail tons of big images), and it looks like it would work (and it almost does). My main problem is this error message whenever I send a SIGNAL from my thread:
QPixmap: It is not safe to use pixmaps outside the GUI thread
I can't figure out how to get around this. I've tried passing a QIcon through my SIGNAL, but that still generates the same error. If it helps, here's the code blocks which deal with this stuff:
The Thumbnailer class:
class Thumbnailer(QtCore.QThread):
def __init__(self, ListWidget, parent = None):
super(Thumbnailer, self).__init__(parent)
self.stopped = False
self.completed = False
self.widget = ListWidget
def initialize(self, queue):
self.stopped = False
self.completed = False
self.queue = queue
def stop(self):
self.stopped = True
def run(self):
self.process()
self.stop()
def process(self):
for i in range(self.widget.count()):
item = self.widget.item(i)
icon = QtGui.QIcon(str(item.text()))
pixmap = icon.pixmap(72, 72)
icon = QtGui.QIcon(pixmap)
item.setIcon(icon)
The part which calls the thread (it occurs when a set of images is dropped onto the list box):
self.thread.images.append(f)
item = QtGui.QListWidgetItem(f, self.ui.pageList)
item.setStatusTip(f)
self.thread.start()
I'm not sure how to handle this kind of stuff, as I'm just a GUI newbie ;)
Thanks to all.
After many attempts, I finally got it. I can't use a QIcon or QPixmap from within a non-GUI thread, so I had to use a QImage instead, as that transmits fine.
Here's the magic code:
Excerpt from the thumbnailer.py QThread class:
icon = QtGui.QImage(image_file)
self.emit(QtCore.SIGNAL('makeIcon(int, QImage)'), i, icon)
makeIcon() function:
def makeIcon(self, index, image):
item = self.ui.pageList.item(index)
pixmap = QtGui.QPixmap(72, 72)
pixmap.convertFromImage(image) # <-- This is the magic function!
icon = QtGui.QIcon(pixmap)
item.setIcon(icon)
Hope this helps anyone else trying to make an image thumbnailing thread ;)

Resources