My GUI app has two files: gui.py that contains all the Tkinter objects and controller.py contains the logic. The logic is one main function def automation(): that nests several other functions. The app is very simple it's only one button that calls automation().
I would like to add the print statements and errors that appear in the terminal in the GUI widget so that the user can see what's going on. I can't find a way to do that for imported modules.
gui.py
import tkinter as tk
from tkinter import *
from controller import automation
root = tk.Tk()
frame_button = tk.Frame(root)
button = Button(frame_button, text="Ship", command=lambda:automation())
lower_frame = tk.Frame(root)
terminal = tk.Label(lower_frame)
frame_button.place()
button.place()
lower_frame.place()
terminal.place()
controller.py
def automation():
def folder_cleaner():
print('Folders cleaned')
def dispatch():
print('Dispatch done')
def ship():
print('Shipment successful')
def process():
folder_cleaner()
dispatch()
ship()
process()
This is very simplified but each function has many different kinds of outputs. How can I redirect all of them to gui.py and inside the terminal widget?
To show the output in the UI, I've added an output function in gui.py. So the function can be used in controller.py, I've added a parameter outputFunc when calling automation. This can then be used instead of print to display the strings in the UI.
gui.py
import tkinter as tk
from tkinter import *
from controller import automation
def output(text):
terminal.insert("end", text + "\n")
root = tk.Tk()
frame_button = tk.Frame(root)
button = Button(frame_button, text="Ship", command=lambda:automation(output))
lower_frame = tk.Frame(root)
#Changed to text widget as it is more ideal for this purpose
terminal = tk.Text(lower_frame)
#Changed place to pack so widgets actually display
frame_button.pack()
button.pack()
lower_frame.pack()
terminal.pack()
controller.py
def automation(outputFunc):
def folder_cleaner():
outputFunc('Folders cleaned')
def dispatch():
outputFunc('Dispatch done')
def ship():
outputFunc('Shipment successful')
def process():
folder_cleaner()
dispatch()
ship()
process()
Here is one approach to Your issue (this works especially well if Your automation runs in a loop or basically is not as fast, it will make sure to update when any change happens):
from tkinter import Tk, Button, Label, Frame
from _thread import start_new_thread
from time import sleep
values = {'random_values': []}
def automation():
for i in range(10):
values['random_values'].append(i)
sleep(3)
def watch_values():
compare = None
while True:
value = str(values['random_values'])
if compare != value:
label.config(text=values['random_values'])
compare = value
root = Tk()
Button(root, text='start', command=lambda: start_new_thread(automation, ())).pack()
label = Label(root)
label.pack()
start_new_thread(watch_values, ())
root.mainloop()
So basically first it starts a thread that watches the values dictionary (it is important for it to interact with tkinter only when there are changes tho because otherwise it will cause issues with tkinter GUI so that is why there is compare).
Whenever there is a change in that particular variable it sets the text of the label as that variable (variable being values['random_values']).
Then there is the automation function. I suggest that You put everything it returns in a dictionary that will be watched by the other thread. You also need to thread Your automation function so that it can work in parallel. (And You can obviously import that function from another file, just add it to the threads, also it may seem weird but those empty tuples there are necessary since that is an argument (in those tuples it is also possible to put the function argument if You have those but in this case there are none))
And You only need one watcher function, just add more compares and checks to that loop and so on (mentioned in case You wanted to create such a function for every key in the dictionary which is completely unnecessary)
Related
I am building an interface in Tkinter in which the main window (let's call it 'root') contains a button (say, 'create'). Furthermore, assume I have already defined a function 'f'. I would like to create the following effect: clicking on 'create' would execute 'f' in the background and at the same time open an indeterminate progress bar in a new window. Moreover, and this is the tricky part for me, I want the progress bar to close automatically after 'f' is done executing. How can I achieve this? Could you please provide a minimal working example? I think that key lies on constructing a proper function to pass as 'command' option to 'create'.
This is what I have thus far. It is not even running properly, as the progress bar runs indefinitely and the task starts being executed only after the progress bar is closed (or after closing 'root'). However, it feels like this is really close, and there is some small issue that I should fix but that I cannot see:
from tkinter import *
from tkinter.ttk import *
import threading
import time
root = Tk() # Main window
def create_command():
stop_flag = threading.Event() # create a flag to stop the progress bar
def f():
# function to do some task
print("Starting task...")
time.sleep(5) # simulate some time-consuming task
print("Task complete.")
stop_flag.set() # set the stop flag to indicate that progress_check() should stop
progress_bar_window = Toplevel(root) # Progress bar window
progress_bar = Progressbar(progress_bar_window, orient= 'horizontal', length= 300, mode= 'indeterminate') # Create progress bar
progress_bar.pack()
progress_bar.start()
def progress_check():
# function to run an infinite loop
while not stop_flag.is_set():
print("Running infinite loop...")
time.sleep(1)
progress_bar.stop()
progress_bar_window.destroy()
progress_bar_window.mainloop() # Start mainloop for progress bar window
# create separate threads to run the functions
thread1 = threading.Thread(target=f, args=())
thread2 = threading.Thread(target=progress_check, args=())
thread1.start() # start executing f
thread2.start() # start the progress_check
# wait for f to finish before stopping the infinite loop
thread2.join()
stop_flag.set() # set the stop flag to indicate that progress_bar() should stop
create_button = Button(root, text= "Create", command= create_command)
create_button.pack()
root.mainloop()
Look at this:
from tkinter import ttk
import tkinter as tk
import threading
import time
root = tk.Tk() # Main window
def create_command():
# create a flag to stop the progress bar
stop_flag = threading.Event()
def f():
print("Starting task...\n", end="")
time.sleep(5)
print("Task complete.\n", end="")
# set the stop flag to indicate that progress_check() should stop
stop_flag.set()
progress_bar_window = tk.Toplevel(root)
progress_bar = ttk.Progressbar(progress_bar_window, orient="horizontal",
length=300, mode="indeterminate")
progress_bar.pack()
progress_bar.start()
def progress_check():
# If the flag is set (function f has completed):
if stop_flag.is_set():
# Stop the progressbar and destroy the toplevel
progress_bar.stop()
progress_bar_window.destroy()
else:
# If the function is still running:
print("Running infinite loop...\n", end="")
# Schedule another call to progress_check in 100 milliseconds
progress_bar.after(100, progress_check)
# start executing f in another thread
threading.Thread(target=f, daemon=True).start()
# Start the tkinter loop
progress_check()
create_button = tk.Button(root, text= "Create", command=create_command)
create_button.pack()
root.mainloop()
Explanation:
To run a loop alongside tkinter, you should use .after, like in this question. I changed progress_check so that tkinter calls it every 100 milliseconds until stop_flag is set. When stop_flag is set, the progressbar stops and the Toplevel is destroyed.
A few minor points:
from ... import * is discouraged
With tkinter, you don't need more than 1 .mainloop() unless you are using .quit(). .mainloop() doesn't stop until all tk.Tk windows have been destroyed.
There is no point in creating a new thread, if you are going to call .join() right after.
First of all, don't use wildcard imports!
Wildcard-imports can lead to name conflicts, for instance swap the wildcard imports from ttk and tkinter. You end up using tkinter buttons even if you want to use ttk buttons. Same issue might appear with PhotoImage and pillow. The magic word is "qualified-names".
Also I like to have some sort of structure in my code, I prefer classes. However, even in a procedural code there can be some sort of structure. For instance:
imports
1.0) built-in modules
1.1) import external modules
1.2) import own modules
Constants and global variables
free functions
main window definitions
...
every logical block can be separated with comments that indicates what the following code might do or represents. This could also be useful to "jump" with the search function of your IDE to the point you want to work next, in larger scripts and modules this becomes handy.
A slightly different version of your code can be found below and it is not intended to be used:
import tkinter as tk
from tkinter import ttk
import threading
import time
def start_worker_thread():
'This function starts a thread and pops up a progressbar'
def generate_waiting_window():
'nested function to generate progressbar'
#disable button to inform user of intended use
start_btn.configure(state=tk.DISABLED)
#toplevel definitions
toplevel = tk.Toplevel(root)
toplevel.focus()
#progressbar definitions
progress = ttk.Progressbar(
toplevel, orient=tk.HORIZONTAL, length=300, mode='indeterminate')
progress.pack(fill=tk.BOTH, expand=True)
progress.start()
return toplevel
def long_blocking_function():
'This function simulates a long blocking call'
stopped = threading.Event()
n = 0
while not stopped.is_set():
n += 1
print('working in turn', n)
time.sleep(0.5)
if n == 10:
stopped.set()
nonlocal thread_info
thread_info = n
#important!! last logical line
toplevel.destroy()
return None
toplevel = generate_waiting_window()
thread_info = None
thread = threading.Thread(target=long_blocking_function)
thread.start()
toplevel.wait_window()
start_btn.configure(state='normal')
result_lbl.configure(text='Result is: '+str(thread_info))
print('thread exited on turn', thread_info)
#Main window definitions
root = tk.Tk()
start_btn = ttk.Button(root, text="Start", command=start_worker_thread)
start_btn.pack()
result_lbl = tk.Label(root, text='Result is: None')
result_lbl.pack()
#start the application
root.mainloop()
#after application is destroyed
While this code is efficient for this simple task, it requires understanding what it does to debug it. That is why you won't find code like this often. It is here for demonstrative purposes. So what is wrong with the code and how does it differ from the meanwhile canonical way of using threads in tkinter.
First of all, it uses nested function. While this might not an issue here, computing the same function over and over again, can slow down your code significantly.
Second it uses tkwait and therefore has some caveats over the linked answer.
Also threading.Event is a low-level primitive for communication, while there are cases you could use it, tkinter offers own tools for it and these should be preferred.
In addition it does not use a threadsafe storage for the data and this could also lead to confusion and non reliable data.
A better approach and a slight improvement to the canonical way can be found here:
import tkinter as tk
from tkinter import ttk
import threading
import sys
import queue
import time
inter_thread_storage = queue.Queue()
temporary_toplevel = None
EXIT = False
def on_thread_ended_event(event):
start_btn.configure(state=tk.NORMAL)
result = inter_thread_storage.get_nowait()
result_lbl.configure(text='Result is: '+str(result))
global temporary_toplevel
temporary_toplevel.destroy()
temporary_toplevel = None
def worker_thread_function():
'Simulates a long blocking function'
n = 0
while n < 10 and not EXIT:
n += 1
print('working in turn', n)
time.sleep(0.5)
if not EXIT:
inter_thread_storage.put(n)
root.event_generate('<<ThreadEnded>>')
def start_worker_thread():
'This function starts a thread and pops up a progressbar'
#toplevel definitions
toplevel = tk.Toplevel(root)
toplevel.focus()
#progressbar definitions
progress = ttk.Progressbar(
toplevel, orient=tk.HORIZONTAL, length=300, mode='indeterminate')
progress.pack(fill=tk.BOTH, expand=True)
progress.start()
#thread definitions
thread = threading.Thread(target=worker_thread_function)
thread.start()
#disable button to inform user of intended use
start_btn.configure(state=tk.DISABLED)
#store toplevel temporary
global temporary_toplevel
temporary_toplevel = toplevel
#Main window definitions
root = tk.Tk()
root.bind('<Destroy>',lambda e:setattr(sys.modules[__name__], 'EXIT', True))
root.bind('<<ThreadEnded>>', on_thread_ended_event)
start_btn = ttk.Button(root, text="Start", command=start_worker_thread)
start_btn.pack()
result_lbl = tk.Label(root, text='Result is: None')
result_lbl.pack()
#start the application
root.mainloop()
#after application is destroyed
This is how it works:
generate a new event
Make sure your toplevel can be reached, with global or alternatives.
store data threadsafe like in a Queue
fire the event and let tkinter call your function safely in the mainloop.
it has a flag for the edge case, where the user closes the main window before the thread finished.
Let me know, if you have questions to my answer.
Following is code for a tkinter listbox, created as a class, and saved as a module named ModListbox:
import tkinter as tk
class Lstbox(tk.Listbox):
def __init__(self,master,listname):
super().__init__(master)
# insert list
self.insert(0,*listname)
# place listbox
self.place(x=10,y=10)
Likewise, following is the simplest code for a main app that imports the module and displays the listbox.
import tkinter as tk
root=tk.Tk()
MyList = ['first','second','third','fourth','fifth']
import ModListbox
NewListbox = ModListbox.Lstbox(master=root,listname=MyList)
root.mainloop()
In order to add functionality to the listbox, the obvious approach is to load the module and create an instance of the class, then to bind the listbox to a function, as follows, within the main application code. So clicking on the listbox triggers an event.
import tkinter as tk
root=tk.Tk()
# function on user selection in listbox
def UserClickedNewListbox(event):
SelectedIndex = NewListbox.curselection()[0]
SelectedText = NewListbox.get(SelectedIndex)
print("You selected ", SelectedText)
MyList = ['first','second','third','fourth','fifth']
import ModListbox
NewListbox = ModListbox.Lstbox(master=root,listname=MyList)
# bind listbox to function
NewListbox.bind('<<ListboxSelect>>',UserClickedNewListbox)
root.mainloop()
However, one reason among many that I'm creating tkinter widgets as classes is to keep as much code in the modules as possible, and reduce the code in the main app. So here is the same module, but with the binding and function included inside the module.
import tkinter as tk
class Lstbox(tk.Listbox):
def __init__(self,master,listname):
super().__init__(master)
# insert list
self.insert(0,*listname)
# place listbox
self.place(x=10,y=10)
# bind user selection to function
self.bind('<<ListboxSelect>>',self.UserClickedListbox)
def UserClickedListbox(self,event):
SelectedIndex = self.curselection()[0]
# How do I trigger an action inside the main app from here?
So now, inside the module itself, a user click on the listbox triggers the function. The function 'knows' the index of the listbox clicked by the user. How, if it is possible at all, would I trigger an event inside the main application, while also passing the selected index? Is this possible? Any advice appreciated.
from tkinter import *
from tkinter.ttk import *
root = Tk()
first_run = True
def update(txt):
global first_run
text1 = Label(root, text='')
if first_run:
text1.pack()
text1['text'] = txt
first_run = False
update('1')
update('2')
update('3')
root.mainloop()
When I run this, the text stays at '1', and the following 2 function calls are ignored. I find out that only if I use pack() again then it will be updated, but it creates a duplicate label and I do not want that.
Of course, I know that I am supposed to use a StringVar, but I have been using this method for all other widgets (buttons, label frames etc) and all of them works. I do not know why this particular case does not work.
Running on Python 3.9.9 on Windows 11
You aren't updating the label, you are creating a new label each time the function is called. To update any widget, use the configure method. For that, you need to create the label outside of the function (or, leave it in the function but add logic so that it's only created once). Usually it's best to create it outside the function so that the function is only responsible for the update.
from tkinter import *
from tkinter.ttk import *
root = Tk()
def update(txt):
text1.configure(text=txt)
text1 = Label(root, text='')
text1.pack()
update('1')
update('2')
update('3')
root.mainloop()
Note: since you call your function multiple times before the window is drawn you'll only see the final value. There are plenty of solutions to that on this site. Without knowing more about what your real program looks like it's hard to recommend the best solution to that problem.
I want to make a GUI command line using the Text widget. For debugging purposes, I am trying to print whatever the user types into the separate GUI window to the system terminal. I know that it is frowned upon to mix GUI and Text Based commands into the same script, but I am just debugging, so forgive me 😉
Here is my code:
from Tkinter import *
main = Tk()
console = Text(main)
console.pack()
main.mainloop()
while True:
text = console.get("1.0", "end-1c")
print(text)
My current issue is that when the mainloop starts, (of course) the while loop doesn't. If I were to move the while loop in front of the mainloop call, it would never call mainloop. I really want it to continuously check for new text.
Is there a way to like "pause" the mainloop, or just carry out the command, maybe on a new thread or something?
I want to avoid using main.after(), but if that is the only way, then so be it. ¯\(°_o)/¯
I recommend using main.after(), as it's the canonical way to do things like this in Tkinter. The following will also ensure that it only tries to print every second, instead of as fast as the console can handle it (as the while loop in your code would do if it worked).
def print_console():
print(console.get("1.0", "end-1c"))
main.after(1000, print_console)
print_console()
main.mainloop()
You can also bind widgets to "Modified"
from Tkinter import *
class TextModified():
def __init__(self):
root = Tk()
self.txt = Text(root)
self.txt.pack()
self.txt.focus_set()
self.txt.bind('<<Modified>>', self.changed)
Button(text='Exit', command=root.quit).pack()
root.mainloop()
def changed(self, value=None):
flag = self.txt.edit_modified()
if flag: # prevent from getting called twice
print "changed called", self.txt.get("1.0", "end-1c")
## reset so this will be called on the next change
self.txt.edit_modified(False)
TM=TextModified()
I'm new to programming, Python, this website, and actually using these kinds of websites in general, so hear me out.
I've been writing a module for a larger program using the tkinter module and ttk module, and when I import my own module into the main program, for some reason none of the ttk stuff works as it should. I mean, it appears, but the style I've written for it (s=ttk.Style(); s.configure...etc.) doesn't change it in anyway. When I run the module on its own, everything works fine. When it's imported into the main program, it just doesn't.
Not only this, but when using entry boxes, I've only just discovered that the way I'd been told to use them, with, for example, var=StringVar() as the textvariable (which again works fine when the module is run on its own), now just leaves the variable var as empty when var.get() is called. Now I've sorted this by just removing all mention of StringVar() (wish I'd known how redundant these really are), but I'd still like to know why importing them in to the main program causes them to malfunction so badly. I would give you some sample code but there's so much I'd struggle to be selective enough...
I'd appreciate any guidance you can offer.
EDIT: Would giving you something like this have helped?
stackoverflowmodule.py
import sys
from tkinter import *
from tkinter import ttk
import time
from random import randint, choice
class Decimals():
def Question1(self):
DECFrame.destroy()
frame1=ttk.Frame(DECmaster, height=height, width=width, style="NewFrame.TFrame")
frame1.pack()
Q1Label=ttk.Label(frame1, text="Question 1:", style="TitleLabel.TLabel")
Q1Label.grid(column=0, row=0, pady=(50,0))
answer=StringVar()
entry1=ttk.Entry(frame1, textvariable=answer)
entry1.grid(column=0, row=1, pady=(200,0))
# Typing in Hello should give a correct answer.
def Question1Attempt():
attempt=answer.get()
if attempt!="Hello":
print("Incorrect")
else:
print("Correct")
button=ttk.Button(frame1, text="Ok", command=Question1Attempt)
button.grid(column=0, row=2, pady=(30,0))
def Start():
global DECmaster
global s
global DECFrame
global DEC
global width
global height
DECmaster = Tk()
width=str(1000)
height=str(800)
x1=str(0)
y1=str(0)
DECmaster.geometry(width+"x"+height+"+"+x1+"+"+y1)
DECmaster.configure(bg="#8afff0")
s=ttk.Style()
s.configure("NewFrame.TFrame", background="#8afff0")
s.configure("TitleLabel.TLabel", foreground= "blue", background="#8afff0")
DECFrame=ttk.Frame(DECmaster, style="NewFrame.TFrame")
DECFrame.pack()
TitleLabel=ttk.Label(DECFrame, text="Test for Decimals", style="TitleLabel.TLabel")
TitleLabel.grid(column=1, row=0, pady=(50,0), sticky=N)
DEC=Decimals()
button=ttk.Button(DECFrame, text="Start", command=DEC.Question1)
button.grid(column=2, row=2, pady=(200,0), sticky=N)
DECmaster.mainloop()
stackoverflowprogram.py
from tkinter import *
from tkinter import ttk
import time
import stackoverflowmodule
root = Tk()
width=str(1000)
height=str(800)
x1=str(0)
y1=str(0)
##width=str(1228)
##height=str(690)
##x1=str(-1)
##y1=str(-22)
root.geometry(width+"x"+height+"+"+x1+"+"+y1)
root.configure(bg="#8afff0")
s=ttk.Style()
s.configure("NewFrame.TFrame", background="#8afff0")
s.configure("TitleLabel.TLabel", foreground= "blue", background="#8afff0")
Testframe=ttk.Frame(root, height=height, width=width, style="NewFrame.TFrame")
Testframe.pack()
Titlelabel=ttk.Label(Testframe, text="Start Test:", style="TitleLabel.TLabel")
Titlelabel.grid(column=0, row=0, pady=(50,0))
def StartTest():
stackoverflowmodule.Start()
button=ttk.Button(Testframe, text="Start", command=StartTest)
button.grid(column=0, row=1, pady=(100,0))
root.mainloop()
I realise there's an awful lot there, but I couldn't really demonstrate my point without it all. Thanks again.
The root of your problem is that you're creating more than once instance of Tk. A Tkinter app can only have a single instance of of the Tk class, and you must call mainloop exactly once. If you need additional windows you should create instances of Toplevel (http://effbot.org/tkinterbook/toplevel.htm).
If you want to create modules with reusable code, have your modules create subclasses of Frame (or Toplevel if you're creating dialos). Then, your main script will create an instance of Tk, and place these frames in the main window or in subwindows.
If you want to sometimes use your module as a reusable component and sometimes as a runnable program, put the "runnable program" part inside a special if statement:
# module1.py
import Tkinter as tk
class Module1(tk.Frame):
def __init__(self, *args, **kwargs):
label = tk.Label(self, text="I am module 1")
label.pack(side="top", fill="both", expand=True)
# this code will not run if this module is imported
if __name__ == "__main__":
root = tk.Tk()
m1 = Module1(root)
m1.pack(side="top", fill="both", expand=True)
In the above code, if you run it like python module1.py, the code in that final if statement will run. It will create a root window, create an instance of your frame, and make that frame fill the main window.
If, however, you import the above code into another program, the code in the if statement will not run, so you don't get more than one instance of Tk.
Let's assume you have two modules like the above, and want to write a program that uses them, and each should go in a separate window. You can do that by writing a third script that uses them both:
# main.py
import Tkinter as tk
from module1 import Module1
from module2 import Module2
# create the main window; every Tkinter app needs
# exactly one instance of this class
root = tk.Tk()
m1 = Module1(root)
m1.pack(side="top", fill="both", expand=True)
# create a second window
second = tk.Toplevel(root)
m2 = Module2(second)
m2.pack(side="top", fill="both", expand=True)
# run the event loop
root.mainloop()
With the above, you have code in two modules that can be used in three ways: as standalone programs, as separate frames within a single window, or as separate frames within separate windows.
You can't create two instances of tkinter.Tk. If you do, one of two things will happen.
Most of the code in the script may just not run, because it's waiting for the module's mainloop to finish, which doesn't happen until you quit.
If you structure things differently, you'll end up with two Tk instances, only one of which is actually running. Some of the code in your script will happen to find the right Tk instance (or the right actual Tk objects under the covers), because there's a lot of shared global stuff that just assumes there's one Tk "somewhere or other" and manages to find. But other code will find the wrong one, and just have no effect. Or, occasionally, things will have the wrong effect, or cause a crash, or who knows what.
You need to put the top-level application in one place, either the module or the script that uses it, and have the other place access it from there.
One way to do this is to write the module in such a way that its code can be called with a Tk instance. Then, use the __main__ trick so that, if you run the module directly as a script (rather than importing it from another script), it creates a Tk instance and calls that code. Here's a really simple example.
tkmodule.py:
from tkinter import *
def say_hi():
print("Hello, world!")
def create_interface(window):
hi = Button(window, text='Hello', command=say_hi)
hi.pack()
if __name__ == '__main__':
root = Tk()
create_interface(root)
root.mainloop()
tkscript.py:
from tkinter import *
import tkmodule
i = 0
def count():
global i
i += 1
print(i)
def create_interface(window):
countbtn = Button(window, text='Count', command=count)
countbtn.pack()
root = Tk()
create_interface(root)
window = Toplevel(root)
tkmodule.create_interface(window)
root.mainloop()
Now, when you run tkscript.py, it owns one Tk instance, and passes it to its own create_frame and to tkmodule.create_frame. But if you just run tkmodule.py, it owns a Tk instance, which it passes to its own create_frame. Either way, there's exactly one Tk instance, and one main loop, and everyone gets to use it.
Notice that if you want two top-level windows, you have to explicitly create a Toplevel somewhere. (And you don't want to always create one in tkmodule.py, or when you run the module itself, it'll create a new window and leave the default window sitting around empty.)
Of course an even simpler way to do this is to put all of your GUI stuff into modules that never create their own Tk instance, and write scripts that import the appropriate modules and drive them.