Running complicated code inside of pySimpleGUI? - python

I'm trying to run some code inside of a GUI, where I run a function after I get a few text inputs. however the function I am trying to run is actually really complicated, so when it runs, it makes the entire gui freeze up for 10-15 seconds before continuing.
How can I make it so that when I hit the run button, it doesn't freeze up the entire GUI waiting for the function to complete?
I do understand that there is a way to make functions threaded, however, I don't know how to implement that?
An example of how I can wrap a function to make it a threaded one would be great.
The code below gives an example of the problem that I am dealing with.
import PySimpleGUI as sg
import time
def simple_gui():
layout = [ [sg.T('try clicking "do something" and move the window')],
[sg.Button('do something'), sg.Button('Exit')] ]
w = sg.Window('test', layout)
while True:
events, values = w.read()
if events == 'do something':
# If you hit the button "do something":
# run a function that takes 30 seconds to complete.
time.sleep(30)
if events == sg.WIN_CLOSED or events == 'Exit':
break
w.close()
simple_gui()

There are a number of examples of how you can use threads to perform "long operations" using PySimpleGUI. You'll find the demo programs located at http://Demos.PySimpleGUI.org . There are at least 6 sample programs labeled as being multi-threaded examples.
Some are also available on Trinket to run online. This one shows how to run a thread and then wait for it to complete:
https://pysimplegui.trinket.io/demo-programs#/multi-threaded/multi-threaded-long-task-simple
Here's the code that you'll find there.
#!/usr/bin/python3
import threading
import time
import PySimpleGUI as sg
"""
DESIGN PATTERN - Multithreaded Long Tasks GUI using shared global variables
Presents one method for running long-running operations in a PySimpleGUI environment.
The PySimpleGUI code, and thus the underlying GUI framework, runs as the primary, main thread
The "long work" is contained in the thread that is being started. Communicating is done (carefully) using global variables
There are 2 ways "progress" is being reported to the user.
You can simulate the 2 different scenarios that happen with worker threads.
1. If a the amount of time is known ahead of time or the work can be broken down into countable units, then a progress bar is used.
2. If a task is one long chunk of time that cannot be broken down into smaller units, then an animated GIF is shown that spins as
long as the task is running.
"""
total = 100 # number of units that are used with the progress bar
message = '' # used by thread to send back a message to the main thread
progress = 0 # current progress up to a maximum of "total"
def long_operation_thread(seconds):
"""
A worker thread that communicates with the GUI through a global message variable
This thread can block for as long as it wants and the GUI will not be affected
:param seconds: (int) How long to sleep, the ultimate blocking call
"""
global message, progress
print('Thread started - will sleep for {} seconds'.format(seconds))
for i in range(int(seconds * 10)):
time.sleep(.1) # sleep for a while
progress += total / (seconds * 10)
message = f'*** The thread says.... "I am finished" ***'
def the_gui():
"""
Starts and executes the GUI
Reads data from a global variable and displays
Returns when the user exits / closes the window
"""
global message, progress
sg.theme('Light Brown 3')
layout = [[sg.Text('Long task to perform example')],
[sg.Output(size=(80, 12))],
[sg.Text('Number of seconds your task will take'),
sg.Input(key='-SECONDS-', size=(5, 1)),
sg.Button('Do Long Task', bind_return_key=True),
sg.CBox('ONE chunk, cannot break apart', key='-ONE CHUNK-')],
[sg.Text('Work progress'), sg.ProgressBar(total, size=(20, 20), orientation='h', key='-PROG-')],
[sg.Button('Click Me'), sg.Button('Exit')], ]
window = sg.Window('Multithreaded Demonstration Window', layout)
thread = None
# --------------------- EVENT LOOP ---------------------
while True:
event, values = window.read(timeout=100)
if event in (None, 'Exit'):
break
elif event.startswith('Do') and not thread:
print('Thread Starting! Long work....sending value of {} seconds'.format(float(values['-SECONDS-'])))
thread = threading.Thread(target=long_operation_thread, args=(float(values['-SECONDS-']),), daemon=True)
thread.start()
elif event == 'Click Me':
print('Your GUI is alive and well')
if thread: # If thread is running
if values['-ONE CHUNK-']: # If one big operation, show an animated GIF
sg.popup_animated(sg.DEFAULT_BASE64_LOADING_GIF, background_color='white', transparent_color='white', time_between_frames=100)
else: # Not one big operation, so update a progress bar instead
window['-PROG-'].update_bar(progress, total)
thread.join(timeout=0)
if not thread.is_alive(): # the thread finished
print(f'message = {message}')
sg.popup_animated(None) # stop animination in case one is running
thread, message, progress = None, '', 0 # reset variables for next run
window['-PROG-'].update_bar(0,0) # clear the progress bar
window.close()
if __name__ == '__main__':
the_gui()
print('Exiting Program')

Related

Python Tkinter changing UI from the main thread VS new thread

In my learning python process, I came across the typical freezing problem when main thread is blocked by a long running function. The solution I found was basically starting a new thread. I ended up having 2 ways that seemed to be working correctly, but I would love to know if my understanding is correct.
The first way I believe the pb.destory() is an example of updating UI from a non-main thread
# --- functions ---
def longFunction():
for i in range(10):
print(i)
time.sleep(0.25)
# I believe this is updating the UI from the non-main thread (remove the progress bar)
pb.destroy()
def createNewThread():
# I am expecting the prgoressbar animation to not get blocked/freeze.
pb.start(10)
pb.pack()
thread = threading.Thread(target=longFunction)
thread.daemon = True
thread.start()
root = tk.Tk()
pb = Progressbar(root,mode='indeterminate')
tk.Button(root,text='START', command=createNewThread).pack()
root.mainloop()
The second way, I basically tried to use after() with a flag that I checks on periodically. I believe in this one the UI update happens in the main thread
# --- functions ---
def longFunction():
for i in range(10):
print(i)
time.sleep(0.25)
global isDone
isDone = True
# Check on isDone flag every 100 ms
def checkFlag():
global isDone
if isDone:
# I believe this is updating the UI from the main thread (remove the progress bar)
pb.destroy()
else:
root.after(100,checkFlag)
def createNewThread():
# I am expecting the prgoressbar animation to not get blocked/freeze.
pb.start(10)
pb.pack()
thread = threading.Thread(target=longFunction)
thread.daemon = True
thread.start()
root.after(100,checkFlag)
# flag
isDone = False
root = tk.Tk()
pb = Progressbar(root,mode='indeterminate')
tk.Button(root,text='START', command=createNewThread).pack()
root.mainloop()
My questions are:
1- Are my assumptions correct where the first way is updating the UI from non-main thread and the 2nd way is updating the UI from the main thread?
2- Is there an issue in updating the UI from a non-main thread ( I know in WPF/C# it causes too many problems)
3- Is there a better solution?

A confirmation message that disappears pyqt5 [duplicate]

This question already has answers here:
Equivalent to time.sleep for a PyQt application
(5 answers)
Closed 1 year ago.
I would like to display a confirmation image like below, which disappears in 2s after being launched. I can display the image but I cannot make it disappear afterwards. I tried to use a sleep (2) but in this case the image turns all black for every 2 seconds. thank you for helping me please
Your application turns black, because the event loop is not running.
Qt runs by having an event loop run forever. It waits for events and processes them as they come in the queue. The event loop is getting an event, calling your function, and waiting for your function to finish until it moves on to running the next event. Your function shows the window/widget/dialog, then sits in time.sleep for 2 seconds. While it is sitting in time.sleep the Qt Event Loop is still waiting for your function to end to process more events.
There are 3 ways to handle this situation.
QTimer (recommended for your situation).
Show your widget and tell a timer to call your function in 2 seconds.
This will make your function exit right away, so the event loop can continue processing
After 2 seconds the timer will call the close function
Thread (threads are really for I/O like TCP Sockets).
QApplication.processEvents()
Show your dialog and run a loop waiting for 2 seconds.
While the loop is running and checking if 2 seconds has passed tell the event loop to process events.
QTimer - you simply show your window then have a timer call a function to close your window.
self.widg = ...
self.widg.show()
self.widg.raise_() # if already show bring to top
def close_and_delete_widg():
self.widg.close()
self.widg.setParent(None) # Remove reference
self.widg.deleteLater()
self.widg = None # Remove python reference count.
self.tmr = QtCore.QTimer()
self.tmr.setSingleShot(True)
self.tmr.timeout.connect(close_and_delete_widg)
self.tmr.start(2000) # 2 sec
I made a library to help run things on approximate timeouts qt_thread_updater. This library works by continuously running a timer and calling function that were posted. You basically tell it to run a function, and it will run a function in the main event loop later. The delay function is not accurate. This library was made more for threading. However, it makes it so you don't need to manage your timer.
from qt_thread_updater import get_updater
self.widg = ...
self.widg.show()
self.widg.raise_() # if already show bring to top
def close_and_delete_widg():
self.widg.close()
self.widg.setParent(None) # Remove reference
self.widg.deleteLater()
self.widg = None # Remove python reference count.
get_updater().delay(2, close_and_delete_widg) # After approximately 2 seconds call
Threading - I am going to skip, because you don't need it for your use case.
QApplication.processEvents() - This is not really recommended. It can cause issues, but may still work. Essentially, the event loop is waiting for your function to finish. If you call QApplication.processEvents() you are telling your application to process more events while you are currently waiting for this event to finish.
self.widg = ...
self.widg.show()
self.widg.raise_() # if already show bring to top
start = time.time()
while (time.time() - start) <= 2: # Sec or msec?
QtCore.QApplication.processEvents() # QtCore.QApplication.instance().processEvents()
# Close and delete the widget
self.widg.close()
self.widg.deleteLater()
self.widg = None

Setting variables which is not entered in GUI and "Not Responding" Problem

I wanted to write a program that moves the mouse cursor and presses the shift key so that the computer won't be locked. The Problem is I want that if the user doesn't set two variables they should be automatically 0 and 1 but it seems I am missing something. The other thing that I can't understand is when I start the program if I don't click on it everything is ok, but if I click on the program's window it says "Not Responding" but the program is running. I can't understand what I am doing wrong here. Below is my code:
#!/usr/bin/python
import pyautogui
import time
import sys
import os
import PySimpleGUI as sg
from datetime import datetime
def main():
sg.theme('DarkAmber')
layout = [ [sg.Text('Please enter the time intervall between the movements:', size = (45,1)), sg.Input(key='-IT-', enable_events=True)],
[sg.Text('Please enter how long should the script run:', size = (45,1)), sg.Input(key='-DURATION-', enable_events=True)],
[sg.Button('Start'), sg.Button('Stop')],
[sg.Output(size=(60,15))] ]
window = sg.Window('Press to start to move!', layout, size=(450,250), element_justification='right')
while True:
event, values = window.read()
if event in (sg.WIN_CLOSED, 'Stop'):
break
if event == '-IT-' and values['-IT-'] and values['-IT-'][-1] not in ('0123456789'):
window['-IT-'].update(values['-IT-'][:-1])
if event == '-DURATION-' and values['-DURATION-'] and values['-DURATION-'][-1] not in ('0123456789'):
window['-DURATION-'].update(values['-DURATION-'][:-1])
elif event == 'Start':
if values['-IT-'] == "" and values['-DURATION-'] == "":
window['-IT-'].update(1)
window['-DURATION-'].update(0)
elif values['-IT-'] != "" and values['-DURATION-'] == "":
window['-DURATION-'].update(0)
elif values['-IT-'] == "" and values['-DURATION-'] != "":
window['-IT-'].update(1)
move(numMin=int('0'+values['-IT-']), numDuration=int('0'+values['-DURATION-']))
window.close()
main()
Edit:
I've just cut out the unnecessary part of the code.
So if I'm not misunderstanding, I need to use a thread, the second question is for me unclear can I typecast an empty string without adding zero (0) to it? Because when I try just typecast it doesn't work, and if I add a zero the behavior of the code is changing.
Operations That Take a "Long Time"
If you're a Windows user you've seen windows show in their title bar "Not Responding" which is soon followed by a Windows popup stating that "Your program has stopped responding". Well, you too can make that message and popup appear if you so wish! All you need to do is execute an operation that takes "too long" (i.e. a few seconds) inside your event loop.
You have a couple of options for dealing this with. If your operation can be broken up into smaller parts, then you can call Window.Refresh() occasionally to avoid this message. If you're running a loop for example, drop that call in with your other work. This will keep the GUI happy and Window's won't complain.
If, on the other hand, your operation is not under your control or you are unable to add Refresh calls, then the next option available to you is to move your long operations into a thread.
The "Old Way"
There are a couple of demo programs available for you to see how to do this. You basically put your work into a thread. When the thread is completed, it tells the GUI by sending a message through a queue. The event loop will run with a timer set to a value that represents how "responsive" you want your GUI to be to the work completing.
The "New Way" - Window.write_event_value
This new function that is available currently only in the tkinter port as of July 2020 is exciting and represents the future way multi-threading will be handled in PySimpleGUI (or so is hoped).
Previously, a queue was used where your event loop would poll for incoming messages from a thread.
Now, threads can directly inject events into a Window so that it will show up in the window.read() calls. This allows a your event loop to "pend", waiting for normal window events as well as events being generated by threads.
You can see this new capability in action in this demo: Demo_Multithreaded_Write_Event_Value.py
Here is that program for your inspection and education. It's SO nice to no longer poll for threaded events.
import threading
import time
import PySimpleGUI as sg
"""
Threaded Demo - Uses Window.write_event_value communications
Requires PySimpleGUI.py version 4.25.0 and later
This is a really important demo to understand if you're going to be using multithreading in PySimpleGUI.
Older mechanisms for multi-threading in PySimpleGUI relied on polling of a queue. The management of a communications
queue is now performed internally to PySimpleGUI.
The importance of using the new window.write_event_value call cannot be emphasized enough. It will hav a HUGE impact, in
a positive way, on your code to move to this mechanism as your code will simply "pend" waiting for an event rather than polling.
Copyright 2020 PySimpleGUI.org
"""
THREAD_EVENT = '-THREAD-'
cp = sg.cprint
def the_thread(window):
"""
The thread that communicates with the application through the window's events.
Once a second wakes and sends a new event and associated value to the window
"""
i = 0
while True:
time.sleep(1)
window.write_event_value('-THREAD-', (threading.current_thread().name, i)) # Data sent is a tuple of thread name and counter
cp('This is cheating from the thread', c='white on green')
i += 1
def main():
"""
The demo will display in the multiline info about the event and values dictionary as it is being
returned from window.read()
Every time "Start" is clicked a new thread is started
Try clicking "Dummy" to see that the window is active while the thread stuff is happening in the background
"""
layout = [ [sg.Text('Output Area - cprint\'s route to here', font='Any 15')],
[sg.Multiline(size=(65,20), key='-ML-', autoscroll=True, reroute_stdout=True, write_only=True, reroute_cprint=True)],
[sg.T('Input so you can see data in your dictionary')],
[sg.Input(key='-IN-', size=(30,1))],
[sg.B('Start A Thread'), sg.B('Dummy'), sg.Button('Exit')] ]
window = sg.Window('Window Title', layout, finalize=True)
while True: # Event Loop
event, values = window.read()
cp(event, values)
if event == sg.WIN_CLOSED or event == 'Exit':
break
if event.startswith('Start'):
threading.Thread(target=the_thread, args=(window,), daemon=True).start()
if event == THREAD_EVENT:
cp(f'Data from the thread ', colors='white on purple', end='')
cp(f'{values[THREAD_EVENT]}', colors='white on red')
window.close()
if __name__ == '__main__':
main()
Multithreaded Programs
While on the topic of multiple threads, another demo was prepared that shows how you can run multiple threads in your program that all communicate with the event loop in order to display something in the GUI window. Recall that for PySimpleGUI (at least the tkinter port) you cannot make PySimpleGUI calls in threads other than the main program thread.
The key to these threaded programs is communication from the threads to your event loop. The mechanism chosen for these demonstrations uses the Python built-in queue module. The event loop polls these queues to see if something has been sent over from one of the threads to be displayed.
You'll find the demo that shows multiple threads communicating with a single GUI is called:
Demo_Multithreaded_Queued.py
Once again a warning is in order for plain PySimpleGUI (tkinter based) - your GUI must never run as anything but the main program thread and no threads can directly call PySimpleGUI calls.

How can I update Tkinter label from a spawned process (multiprocessing.Process)?

Summary: In Python when I update a Tkinter label text from a spawned process, the label on the GUI is not updated, although the spawned process is executed. How can I make it update from the spawned process?
Im am working with Python 2.7.2 in Lubuntu 20.04
EDIT: I also tried with Python 3.8, had to install python3-tk extra, change a little syntax (parentheses after print command and replacing Tkinter with tkinter), but problem still there looking identical.
END EDIT
Here is my sample code working standalone to try out:
from Tkinter import *
from multiprocessing import Process
# simple Label change invoked from "simple" button
def bnAction_sync():
print "bnAction_sync"
changeLabel()
print "bnAction_sync done"
# asynchronous label change invoked from Async button
def bnAction_async():
print "bnAction_async"
p = Process(target=changeLabel)
p.start()
print "bnAction_Async done"
def changeLabel():
print "change label"
lbl['text'] = "Text changed"
### Apr 19 2021:
### uncommenting the following line really updates label but makes program crash ###
# root.update_idletasks
print "change label done"
root = Tk()
btnSync = Button(root, text="simple", command=bnAction_sync)
btnSync.pack()
btnAsync = Button(root, text="async", command=bnAction_async)
btnAsync.pack()
lbl = Label(root, text="Initial text")
lbl.pack()
root.mainloop()
If I press the "simple" button, text is updated in label. All good.
But:
If I press "async" button,
as you can verify by the prints I have provided, the asynchronous process starts,
the label text updation line is executed.
But: Here is my problem: The label on the GUI is not displaying the updated text.
The reason I want to do it this way:
Because I am starting a long running spawned process, after which I want to update the label. All other processes however should run in parallel. So I created a function f, containing the long running function and the label update function sequentially. I want to call f asynchronously.
So in principle:
def longprocess():
code...
def updatelabel_after_longprocess():
code...
def f():
longprocess()
updatelabel_after_longprocess()
p = Process(target=f)
p.start()
do other things immediately
Somewhere I read, that refresh is suspended, while a script is still running.
I tried some p.join inserts with no luck.
Please help, thanks!
It's unlikely that you'll be able to make updating your label from another process work. It might be possible, but it will be very complicated. What I'd suggest instead is that you make a thread that launches the expensive code in another process, and then waits to update the GUI until after the process is done:
from multiprocessing import Process
from threading import Thread
def longprocess():
# do whatever you need here, it can take a long time
def updatelabel_after_longprocess():
# do whatever GUI stuff you need here, this will be run in the main process
def thread_helper():
process = Process(target=longprocess)
process.start()
process.join() # this waits for the process to end
updatelabel_after_longprocess()
if __name__ == "__main__":
t = Thread(target=thread_helper)
t.start()
# do whatever else you have to do in parallel here
t.join()

Python - How do I continuously repeat a sequence without a While loop and still be able to stop the sequence at any time

I have a Raspberry Pi with the Piface adaptor board. I have made a GUI which controls the LED's on the Piface board.
I wrote a small piece of code to make the LED's run up and down continuously, like Knight Riders car, using a While loop.
I then wrote another piece of code that created a GUI. In the GUI is a button that starts the LED's running up and down continuously with the While loop piece of code.
What I want to do is to have that GUI button start the LED running sequence, and then the same button stop the sequence at any time.
I do understand that the code is sitting/stuck in the While loop. And hence any buttons in the GUI are not going to have an effect.
So is there a better way of doing it? Any pointers would be appreciated.
Thanks in advance.
Another option is to run the LED while loop in a separate thread. Like in
the next code. The while loop is stopped by toggling the shared led_switch
variable.
"""
blinking LED
"""
import tkinter as tk
import threading
import time
led_switch=False
def start_stop():
global led_switch
led_switch=not led_switch
if led_switch:
t=threading.Thread(target=LED)
t.start()
def LED():
while led_switch:
print('LED on')
time.sleep(1)
print('LED off')
time.sleep(1)
root=tk.Tk()
button=tk.Button(root,command=lambda: start_stop(),text='start/stop')
button.pack()
tk.mainloop()
If you have a while loop and a GUI you can use generators to still use the loop and let the GUI run properly.
I sketch the Idea here and create an example for the Tkinter GUI.
You want to write your code as a loop and still use it in a GUI:
from Tkinter import *
from guiLoop import guiLoop # https://gist.github.com/niccokunzmann/8673951
#guiLoop
def led_blink(argument):
while 1:
print("LED on " + argument)
yield 0.5 # time to wait
print("LED off " + argument)
yield 0.5
t = Tk()
led_blink(t, 'shiny!') # run led_blink in this GUI
t.mainloop()
Output while the GUI is responsive:
LED on shiny!
LED off shiny!
LED on shiny!
LED off shiny!
...
Sadly Tkinter is the only GUI I know and it is a bad example because you can always update the GUI in your loop with the update() method of GUI elements:
root = Tk()
while 1:
print("LED on")
t = time.time() + 0.5
while t > time.time(): root.update()
print("LED off")
t = time.time() + 0.5
while t > time.time(): root.update()
But with such a guiLoop you can have multiple loops:
t = Tk()
led_blink(t, 'red')
led_blink(t, 'blue')
led_blink(t, 'green')
t.mainloop()
Here are some examples for starting and stopping the loop with a button.
If you're using Tkinter, there's a very easy pattern for running a loop. Given that the UI (in just about every UI toolkit) is already running an infinite loop to process events, you can leverage this to run code periodically.
Let's assume you have a python object "led" which has a method for toggling it on and off. You can have it switch from on to off every 100ms with something as simple as these three lines of code:
def blink(led):
led.toggle()
root.after(100, blink, led)
The above code will run forever, causing the led to blink every 100ms. If you want to be able to start and stop the blinking with a button, introduce a flag:
def blink(led):
if should_blink:
led.toggle()
root.after(100, blink, led)
When you set the toggle to True, the led will start blinking. When it's False, it will stop blinking.
The main thing to take away from this is that you already have an infinite loop running, so there's no need to create one of your own, and no need to use something as complex as threading. Simply create a function that does one frame of animation, or calls some function or does some unit of work, then have the function request that it be run again in the future. How far in the future defines how fast your animation or blink will run.

Categories

Resources