I have been trying to update tkinter canvas text based on an external event (not bindings to keyboard event).
For eg I have a canvas text set to "Hello world", suppose now I call the update funtion updateUI("good bye"), the canvas text should change to the data that is passed in the updateUI(data) funtion.
Another example to explain my question would be as follows, Suppose I have a for loop
for i in range(5):
updateUI(i)
Here, the canvas text changes dynamically based on the value supplied;(The text will be set to 1 2 3 4 5) I'd like to send the data externally and update the UI in Tkinter so that the data changes dynamically dependent on an external event, such as the for loop in this example.
Here is a working model,
import tkinter as tk
import threading
import time
class gui:
def __init__(self, master, event):
self.master = master
self.event = event
self.i =0
self.canvas= tk.Canvas(master, width= 1000, height= 750, bg="SpringGreen2")
self.id = self.canvas.create_text(300, 50, text="HELLO WORLD", fill="black", font=('Helvetica 15 bold'))
self.canvas.pack()
self.eventCheck()
def updateUI(self):
self.i+=1
self.canvas.itemconfig(self.id, text=f"Goodbye, world {self.i}")
print(f"updated {self.i}")
def eventCheck(self):
flag = self.event.is_set()
if flag:
self.updateUI()
self.master.after(2000, self.eventCheck)
def timingLoop(event):
while True:
event.set()
time.sleep(2)
event.clear()
time.sleep(2)
def main():
root = tk.Tk()
event = threading.Event()
t = threading.Thread(target=timingLoop, args=(event,))
t.daemon = True
t.start()
app = gui(root, event)
root.mainloop()
if __name__ == "__main__":
main()
Now, I want the freedom of sending the data and updating the UI, that is I should be able to call updateUI(data) from any other file, class, and Tkinter should update the UI based on the data received.