How to run a function in the background of tkinter [duplicate] - python

This question already has an answer here:
Tkinter locks Python when an icon is loaded and tk.mainloop is in a thread
(1 answer)
Closed 7 months ago.
I am new to GUI programming and I want to write a Python program with tkinter. All I want it to do is run a simple function in the background that can be influenced through the GUI.
The function counts from 0 to infinity until a button is pressed. At least that is what I want it to do. But I have no idea how I can run this function in the background, because the mainloop() of tkinter has control all the time. And if I start the function in an endless loop, the mainloop() cannot be executed and the GUI is dead.
I would like to return control back to the mainloop() after each cycle, but how can I get the control back from the mainloop() to the runapp-function without a user-triggered event?
Here is some sample code that kills the GUI:
from Tkinter import *
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.button = Button(frame, text="START", command=self.runapp)
self.button.pack(side=LEFT)
self.hi_there = Button(frame, text="RESTART", command=self.restart)
self.hi_there.pack(side=LEFT)
self.runapp()
def restart(self):
print "Now we are restarting..."
def runapp(self):
counter = 0
while (1):
counter =+ 1
time.sleep(0.1)

Event based programming is conceptually simple. Just imagine that at the end of your program file is a simple infinite loop:
while <we have not been told to exit>:
<pull an event off of the queue>
<process the event>
So, all you need to do to run some small task continually is break it down into bite-sized pieces and place those pieces on the event queue. Each time through the loop the next iteration of your calculation will be performed automatically.
You can place objects on the event queue with the after method. So, create a method that increments the number, then reschedules itself to run a few milliseconds later. It would look something like:
def add_one(self):
self.counter += 1
self.after(1000, self.add_one)
The above will update the counter once a second. When your program initializes you call it once, and from then after it causes itself to be called again and again, etc.
This method only works if you can break your large problem (in your case "count forever") into small steps ("add one"). If you are doing something like a slow database query or huge computation this technique won't necessarily work.

You will find the answer in this other question Tkinter locks python when Icon loaded and tk.mainloop in a thread.
In a nutshell, you need to have two threads, one for tkinter and one for the background task.

Try to understand this example : clock updating in backgroud, and updating GUI ( no need for 2 threads ).
# use Tkinter to show a digital clock
# tested with Python24 vegaseat 10sep2006
from Tkinter import *
import time
root = Tk()
time1 = ''
clock = Label(root, font=('times', 20, 'bold'), bg='green')
clock.pack(fill=BOTH, expand=1)
def tick():
global time1
# get the current local time from the PC
time2 = time.strftime('%H:%M:%S')
# if time string has changed, update it
if time2 != time1:
time1 = time2
clock.config(text=time2)
# calls itself every 200 milliseconds
# to update the time display as needed
# could use >200 ms, but display gets jerky
clock.after(200, tick)
tick()
root.mainloop( )
credits: link to site

I don't have sufficient reputation to comment on Bryan Oakley's answer (which I found to be very effective in my program), so I'll add my experience here. I've found that depending on how long your background function takes to run, and how precise you want the time interval to be, it can be better to put self.after call at the beginning of the recurring function. In Bryan's example, that would look like
def add_one(self):
self.after(1000, self.add_one)
self.counter += 1
Doing it this way ensures that the interval of time is respected exactly, negating any interval drift that might occur if your function takes a long time.

If you don't want to be away from those threads, I would like to give one suggestion for your GUI-
Place the function for your GUI just before the root.mainloop() statement.
Example-
root = tk.Tk()
.
.
graphicsfunction() #function for triggering the graphics or any other background
#function
root.mainloop()
Please up vote if you like.

Related

Python how to make repeat timer GUI

I am learning Python and still in level beginner.
I try to make timer program which the timer will be repeated continuously after certain of time.
I write as follow:
from tkinter import *
import threading
import time
mgui = Tk()
def refresh():
threading.Timer(20, refresh).start()
detik = 19
while detik >= 0:
menit,detik = divmod (detik,60)
timer ='{:02d}:{:02d}'.format(menit, detik)
time.sleep(1)
detik -= 1
refresh_waktu=Entry(mgui, width= 6, font=("Helvetica bold", 40), fg='red', bd=2)
refresh_waktu.place(x=155, y=152)
refresh_waktu.insert(END, str(f"{timer:>6}"))
refresh()
mgui.geometry('450x450')
mgui.title('Test')
mgui.mainloop()
When I run the program, the interface GUI seem delay about 20 seconds although after that the program timer running as my expected.
I try to make the Interface also appear when start the program, but I still fail to do so.
Please if anyone can help me to give some advice or suggestion.
I sincerely thank for your help.
Best regards
Tk, like all GUI systems, is event driven. When you create or modify a window, nothing visible happens. All that does is send messages. It is the job of the main loop to extract and dispatch those messages, and that's where the drawing is done. In your case, you are blocking for 20 seconds before you enter the main loop, so nothing will be drawn until then. You need to use something like mgui.after to request a callback after a second, and use that for your timing.

Python: How do you obtain variables from another script which are constantly being updated

I've made a script that uses a while True loop to constantly update a series of variables based on UDP packets that I am constantly recieving. I want to ultimately create a GUI that displays that data and updates the screen constantly, which I plan to do with tkinter (using my_label.after in a function which then calls itself, not sure if this is a good plan).
Here is some testing scripts that I can't get to work properly:
GUI2.py (my test looping script)
import time
var = 0
while True:
var += 1
time.sleep(0.1)
GUI Testing.py (the script that would be accessing those variables)
from GUI2 import *
import time
print('never')
print(var)
time.sleep(1)
The second script never reaches the print('never') line, I think because it gets stuck in the other script's while True loop and never returns.
How should I go about this? I have one script that I want in a constant loop to update my variables to the correct values based on incoming packets, and then another script updating a tkinter window. I went this way as most examples I could find using Tkinter didn't use any sort of while True loops. Could I just put my packet recieving code inside the Tkinter mainloop, and would that effectively act as a while True?
EDIT (added Tkinter loop that I can't get working):
This opens a Tkinter window, but the label stays at 99, then reopens a window when I close it with the new x value (ie. 98, 97, etc). I want the label to update every second.
import tkinter as tk
import time
x = 99
while True:
root = tk.Tk()
label = tk.Label(root, text=x)
label.pack()
x -= 1
time.sleep(1)
root.mainloop()
Below is a sample script to show you how you can update the value in the label widget at a certain time interval. I have provided you the hyperlinks to help you understand tkinter's methods. Best regards.
Key points:
use the textvariable option of the tk.Label widget.
use tkinter's control variable. I have shown you how to set and get it's value.
you can use tkinter's widget method called .after() without having to explicitly use a while-statement and time.sleep() method. Tkinter has it's own event loop that you can use.
writing your tkinter GUI as a class makes it easier to implement what you need.
Example Script:
import tkinter as tk
class App(tk.Frame):
def __init__( self, master, *args, **kw ):
super().__init__( master )
self.master = master
self.create_label()
self.update_label()
def create_label( self ):
self.var = tk.IntVar() # Holds an int; default value 0
self.label = tk.Label(self, textvariable=self.var ) # Use textvariable not text
self.label.pack()
def update_label( self ):
value = self.get_value()
self.var.set( value ) # Set the label widget textvariable value.
self.after(1000, self.update_label) # Call this method after 1000 ms.
def get_value( self ):
'''To simulate calling a function to return a value'''
value = self.var.get() + 1
return value
if __name__ == "__main__":
root = tk.Tk()
root.geometry('100x100+0+24')
app = App( root )
app.pack()
root.mainloop() #This command activates tkinter's event loop
Edit:
As a clarification, this answer shows how to utilize the .after() and .mainloop() methods in GUI Testing.py, i.e. using tkinter event loop and not use two while-loops, to achieve what you wanted to do. This is a way to simplify your GUI script.
For more sophisticated algorithms, e.g. more than one while-loop is involved, you have to look into using threads(note it has its issues) or more recently I found a way of using python's Asyncio approach to do it. The learning curve for these two approaches is a lot steeper. To use the asyncio approach, you can explore modifying my answer to do what you want.
Best solution is to use threads however If you plan to do in simplest possible manner then implement the main loop inside your Tkinter GUI and once you read the packet simply update it on your GUI in same loop. Here is the Updated and working Code.
import tkinter as tk
import time
def setvalue(self, x):
self.label.config(text=x, )
root.update()
time.sleep(1)
def changevalues(self):
x = 99
self.label = tk.Label(root, text=x)
self.label.pack()
while x >0:
x -= 1
setvalue(root,x)
root = tk.Tk()
changevalues(root)
root.mainloop()

tkinter: ability to click on other buttons while script is running

I have a simple Tkinter gui with about 20 buttons on it. When I click on a button, the script runs for about 5 minutes. During which time, I have to wait until the script stops running to click on the other buttons. Is there a way to setup the window so I can click on other button while the first clicked script is running?
from Tkinter import *
import Tkinter as tk
import time
def function1():
time.sleep(60)
print 'function1'
def function2():
time.sleep(60)
print 'function2'
root = Tk()
w = 450 # width for the Tk root
h = 500# height for the Tk root
frame = Frame(root, width=w,height =h)
button1=Button(frame, text = 'function 1',fg='black',command=function1).grid(row=1,column=1)
button2=Button(frame, text = 'function 2',fg='black',command=function2).grid(row=1,column=2)
frame.pack()
root.mainloop()
I want to be able to click on function2 after while function1 is still running
If you trigger a callback that takes 1 minute to run, you're not returning to the main loop for 1 minute, so the GUI can't respond to anything.
There are two common solutions to this.
The first is to use a background thread:
def function1():
time.sleep(60)
print 'function1'
def function1_background():
t = threading.Thread(target=function1)
t.start()
button1 = Button(frame, text='function 1', fg='black', command=function1_background)
This is simple, but it only works when your code is purely doing background work, not touching any of the tkinter widgets.
The only problem here is that you'd have to def 20 extra functions. You don't want to repeat yourself that much—that's 80 lines of repetitive boilerplate code that gets in the way of seeing the code that matters, and 20 chances to make a stupid bug in copy-pasting that's a pain to track down, and 20 places you have to change if you later decide you want, say, processes instead of threads so the work can parallelize better, or a pool of 4 threads with the background tasks queued up.
You can solve that in a few different ways. See this question for more in-depth explanation, but in short, you get Python to do some of the repetitive work for you.
You can def a single helper function:
def background(func):
t = threading.Thread(target=func)
t.start()
… and then lambda 20 separate function:
button1 = Button(frame, text='function 1', fg='black', command=lambda: background(function1))
Alternatively, you can partially apply the function using partial:
button1 = Button(frame, text='function 1', fg='black', command=functools.partial(background, function1))
Or, if you never want to call the functions except in the background, you can write a decorator and apply it to each function at def time:
def background(func):
#functools.wraps(func)
def wrapper():
t = threading.Thread(target=func)
t.start()
return wrapper
#background
def function1():
time.sleep(60)
print 'function1'
If you can't use threads (e.g., because the background work involves fiddling with your tkinter widgets), the alternative is to restructure your code so that, instead of being one monolithic task that takes 1 minute, it's a bunch of separate tasks that each takes a fraction of a second and schedules the next part:
def function1(count=60):
if count > 0:
time.sleep(0.1)
frame.after(0, function1, count-0.1)
else:
print 'function1'
button1 = Button(frame, text='function 1', fg='black', command=function1)
This always works, if you can find a way to do it. Your real work may not be as easy to divide into 0.1-second chunks as a sleep(60) is.

Why does time.sleep pause tkinter window before it opens

I'm developing a program for a stadium and time.sleep() pauses the program before the window opens instead of when I want it to. What is the explanation for this behavior?
import Tkinter as tk
import time
import random
root = tk.Tk()
label = tk.Label(root, text="Navigating To Seat")
label.pack(pady=10, padx=10)
rand = random.randint(6, 16)
while rand != 0:
label2 = tk.Label(root, text="Foward: " + str(rand) + "m")
label2.pack()
rand = rand - 1
time.sleep(1)
label2.pack_forget()
root.mainloop()
What time.sleep does is suspend the execution of your program. If you do that 6-16 times, for 1 second each time, before ever calling mainloop(), you're asking it to wait for 6-16 seconds before starting up your GUI.
You probably don't understand how event loop programming works. Reading through some Tkinter tutorials should get the idea across nicely. If you want a less Tkinter-focused explanation and more information about the details of what's happening and the different ways to get around it, see Why your GUI app freezes.
At any rate, I think I can guess what you want to do, even though it isn't clear from your question: You want to start the GUI up, and then, every second, replace the Label. To do that, you have to wait while the GUI is running, not before it starts.
But you can't just call sleep while the GUI is running, either. The GUI can't run while your program is asleep (again, that's what sleep means).
The easiest way out of this is to turn your loop into a sequence of function calls, each of which schedules the next one to run a second later, using the after method. For example:
import Tkinter as tk
import random
root = tk.Tk()
label = tk.Label(root, text="Navigating To Seat")
label.pack(pady=10, padx=10)
rand = random.randint(6, 16)
label2 = None
def add_label():
global rand
global label2
if not rand:
root.quit()
if label2:
label2.pack_forget()
label2 = tk.Label(root, text="Foward: " + str(rand) + "m")
label2.pack()
rand = rand - 1
root.after(1000, add_label)
add_label()
root.mainloop()
When you first call add_label(), it creates the initial label, asks Tkinter to call add_label() again in 1000 milliseconds, and returns. So, a second after you start the loop, it gets called again, which creates the next label and asks Tkinter to call it again a second later. This keeps going until you decrement rand all the way to 0, at which point you call quit instead of after, which ends the main loop, which ends the program.
There are other things you probably want to fix about this program. For example, instead of destroying and creating a new Widget label each time, you can just change its text—or, maybe even more simply, make rand an IntVar connected to the label, so just updating rand automatically changes the text. Also, for anything less trivial than this program, you'd probably want to replace the global variables with something cleaner—most Tkinter tutorials show you how to use a Frame subclass by about the second or third example, which gives you a convenient place to organize both widgets and member variables like rand.

Python: Is it possible to create an tkinter label which has a dynamic string when a function is running in background?

I have created a tkinter GUI for my python script. When I run the script, I want a dynamic string in one of the Label widgets on the GUI window, which will display:
"Working."
Then:
"Working.."
then
"Working..."
and then start from "Working." again until the script is completed.
(Actually I'd prefer a progress bar in this area)
Is it possible?
I wrote two simple scripts to help demonstrate how to do what you want. The first is using the label:
import tkinter as tk
root = tk.Tk()
status = tk.Label(root, text="Working")
status.grid()
def update_status():
# Get the current message
current_status = status["text"]
# If the message is "Working...", start over with "Working"
if current_status.endswith("..."): current_status = "Working"
# If not, then just add a "." on the end
else: current_status += "."
# Update the message
status["text"] = current_status
# After 1 second, update the status
root.after(1000, update_status)
# Launch the status message after 1 millisecond (when the window is loaded)
root.after(1, update_status)
root.mainloop()
The next one is using a progressbar:
import tkinter as tk
# You will need the ttk module for this
from tkinter import ttk
def update_status(step):
# Step here is how much to increment the progressbar by.
# It is in relation to the progressbar's length.
# Since I made the length 100 and I am increasing by 10 each time,
# there will be 10 times it increases before it restarts
progress.step(step)
# You can call 'update_status' whenever you want in your script
# to increase the progressbar by whatever amount you want.
root.after(1000, lambda: update_status(10))
root = tk.Tk()
progress = ttk.Progressbar(root, length=100)
progress.pack()
progress.after(1, lambda: update_status(10))
root.mainloop()
Note however that I couldn't do too much with the progressbar script because progressbars are a little tricky and need to be customized to your script exactly. I just wrote it to maybe shed a little light on the subject. The main part of my answer though is the label script.
Yes, it is possible. There are two ways to do it:
Whenever you want to update the label from your code you can call the_widget.configure(the_text). This will change the text of the label.
You can create an instance of a tkinter.StringVar, and assign it to the textvariable attribute of a label. Whenever you change the value of the variable (via the_variable.set(the_text), the label will automatically update.
Note that for either of these to work, the event loop needs to be able to process events (ie: you won't see anything if your function takes a long time to run and you never call update_idletasks or re-enter the event loop).

Categories

Resources