【发布时间】:2017-07-30 18:41:32
【问题描述】:
有人可以帮我吗,我正在做一个关于课堂和在其他线程上运行任务的练习,然后是 tkinter。我想更改另一个班级的标签。无法让我的脚本运行。
我尝试了不同的方法,但在理解从类和线程的继承方面遇到了一些麻烦,所以这只是一个了解更多信息的示例。
from tkinter import *
import tkinter as tk
from tkinter import ttk
import threading
#Gloabl for stopping the run task
running = True
#class 1 with window
class App():
def __init__(self):
#making the window
self.root = tk.Tk()
self.root.geometry("400x400+300+300")
self.root.protocol("WM_DELETE_WINDOW", self.callback)
self.widgets()
self.root.mainloop()
# stop task and close window
def callback(self):
global running
running = False
self.root.destroy()
# all the widgets of the window
def widgets(self):
global labelvar
#startbutton
self.start_button = tk.Button(self.root, text="Start", command=lambda:App2())
self.start_button.pack()
#stopbutton
self.stop_button = tk.Button(self.root, text="Stop", command=lambda:self.stop())
self.stop_button.pack()
#Defining variable for text for label
labelvar = "Press start to start running"
self.label = tk.Label(self.root, text=labelvar)
self.label.pack()
#stop the task
def stop(self):
global running
running = False
#class 2 with task in other thread
class App2(threading.Thread):
def __init__(self):
global running
#check if task can be run
running = True
threading.Thread.__init__(self)
self.start()
def run(self):
#starting random work
for i in range(10000):
print(i)
labelvar = "running"
App.label.pack()
#checking if task can still be running else stop task
if running == False:
break
labelvar = "stopped"
App.label.pack()
#initiate main app
app = App()
【问题讨论】:
-
tkinter本身并不支持多线程。只有主线程可以调用它来更新 GUI——所以当你可以使用线程时,你需要注意这个限制和围绕它的代码。
标签: python multithreading tkinter