tkinter中使用thread

发布时间 2023-03-22 21:09:06作者: 帅胡
import tkinter as tk
from threading import Thread
import datetime
import time

class SampleApp(tk.Tk):
	def __init__(self):
		tk.Tk.__init__(self)

		# Make a StringVar that will contain the value
		self.value = tk.StringVar()

		# Make a label that will show the value of self.value
		self.label = tk.Label(self, textvariable=self.value).pack()


		# Make a thread that will run outside the tkinter program
		self.thread = Thread(target=self.show_time)

		# set daemon to True (This means that the thread will stop when you stop the tkinter program)
		self.thread.daemon = True

		# start the thread
		self.thread.start()

		tk.Button(self, text="Click me", command=lambda: print("Hello World")).pack()

	def show_time(self):
		# The thread will execute this function in the background, so you need to while loop to update the value of self.value
		while True:
			# Get the time (in your case, you need to get the api data)
			data = datetime.datetime.now().strftime('Time: %H:%M:%S, Milliseconds: %f')

			# Update the StringVar variable
			self.value.set(data)

			# Pause the while loop with 1 second, so you can set an interval to update your value
			time.sleep(1)

# rest of your code.
root = SampleApp()
root.mainloop()