In python, i want to add the Message 2 to the Tkinter window if a condition is given. In this example I use value of X (time) as a multiprocess, but once in the loop of the Tkinter root I cant give the new Message (2).
from tkinter import *
import time as t
from threading import Thread
def time1():
global x
x = 0
while x<3:
t.sleep(1)
x = 1
def gui():
root = Tk()
Label(root, text=("Message 1")).pack()
if x == 2:
Label(root, text=("Message 2")).pack()
root.mainloop()
generator = Thread(target=time1)
processor1 = Thread(target=gui)
generator.start()
processor1.start()
generator.join()
CodePudding user response:
In your gui
function, you are only testing for the value of x
once, just before entering the mainloop
. If x
becomes 2 later, nothing will happen.
Try this instead:
import tkinter as tk
import time
from threading import Thread
def time1():
"""
Add a second Label after a certain condition is met.
"""
x = 0
while x < 3:
time.sleep(1)
x = 1
tk.Label(root, text="Message 2").pack()
if __name__ == "__main__":
root = tk.Tk()
tk.Label(root, text="Message 1").pack()
generator = Thread(target=time1)
generator.start()
root.mainloop()
From the Python tutorial:
Note that in general the practice of importing
*
from a module or package is frowned upon, since it often causes poorly readable code. However, it is okay to use it to save typing in interactive sessions.
It is considered good practice with tkinter
that the GUI is run from the main thread. This is to take ensure that everything works if tkinter
is not built with multithreading support.