Passing a link by a widget to a function
In the following Python application, my main GUI window Tkinter
does not have several buttons (which in turn call some functions) and text widgets. Text widgets need to be updated from the function called by button click.
I tried to send text to a function, but I don't see the updated values ββin the text in sequential order. Rather, it first populates the function (or loop) and then updates all the values ββtogether at the end. I want to see them one by one when the corresponding statement is executed.
from Tkinter import *
import Tkinter as tk
from functools import partial
import time
class mainWindow:
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
self.stat0 = tk.Text(self.frame,bg='cyan', font=("Helvetica", 10), width = 8, height = 1)
self.stat0.grid(row=2, column=0, sticky=W)
self.b0 = tk.Button(self.frame,bg='black',fg='white',text='LOAD',font=("Helvetica", 8),command=lambda:self.loadStatus(self.stat0))
self.b0.grid(row = 1, column = 0, sticky=W)
self.frame.grid()
def loadStatus(self,stat):
stat.insert(END,5)
time.sleep(1)
# stat.delete(1.0,END)
stat.insert(END,"hi")
# stat.delete(1.0,END)
time.sleep(1)
stat.insert(END,0)
if __name__ == '__main__':
#main()
root = tk.Tk()
app = mainWindow(root)
root.mainloop()
Here, when the button is clicked load
, I can see all the values ββ(which are assigned sequentially) in one go after the function ends and after the delay is inserted.
Please help me to update the text input one at a time as instructed.
source to share
You should use after to execute some time triggered events in tkinter. I changed my code to use it:
from Tkinter import *
import Tkinter as tk
from functools import partial
class mainWindow:
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
self.stat0 = tk.Text(self.frame,bg='cyan',
font=("Helvetica", 10), width = 8, height = 1)
self.stat0.grid(row=2, column=0, sticky=W)
self.b0 = tk.Button(self.frame,bg='black',fg='white',text='LOAD',
font=("Helvetica", 8),command=self.loadStatus)
self.b0.grid(row = 1, column = 0, sticky=W)
self.frame.grid()
def loadStatus(self):
self.stat0.insert(END, "hi")
self.frame.after(1000, self.loadStatus)
if __name__ == '__main__':
#main()
root = tk.Tk()
app = mainWindow(root)
root.mainloop()
The idea is what's loadStatus
called "recursively" on after
. Now it runs forever, but you can add some counters, etc. to check when the recursive calls should stop. Hope this helps.
source to share