Dec-23-2020, 02:57 PM
Code located after "root.mainloop()" is not going to execute until you close the root window. But you can't just move your while loop ahead of "root.mainloop()" because that prevents tkinter from running. What you need to do is simultaneously let mainloop() run while processing data from your serial port. There is probably a framework for doing this kind of thing built into your Raspberry Pi libraries. Look at the serial port library for some way to call a function when data is available on the serial port. Failing that, look for some kind of scheduler that will execute a function periodically.
You could always use the ".after" function from tkinter. In the example below I used root.after() in the random_rectangle() function to execute the function 10 times a second while letting mainloop() run at the same time.
You could always use the ".after" function from tkinter. In the example below I used root.after() in the random_rectangle() function to execute the function 10 times a second while letting mainloop() run at the same time.
import random from tkinter import * import time rectangle = None root = Tk() root.geometry("200x200") canvas = Canvas( root, width = 1280, height = 800) canvas.pack(fill = "both", expand = True) canvas.create_image(0, 0, anchor = "nw") def random_rectangle(): global rectangle if rectangle is not None: canvas.delete(rectangle) x = random.randint(0, 200) // 50 * 50 y = random.randint(0, 200) // 50 * 50 rectangle = canvas.create_rectangle(x, y, x+50, y+50, fill='red') root.after(100, random_rectangle) random_rectangle() root.mainloop() print('This is not executed until you close the root window')