0
我一直在掙扎着線程,排隊和兩個類之間傳遞數據的概念。我在這裏和在互聯網上搜索,並沒有發現任何給我我需要的東西。Python 3線程和排隊
基本上我有一些代碼可以在一個線程中打開一個gui,當你點擊開始時它會打開另一個重要的線程。
我有兩個最大的問題是:
- 如何更新在GUI類的標籤,以顯示其他類的輸出?
- 如何停止計數線程並重新啓動它?
這是據我可以得到:
import tkinter as tk
import threading
import queue
import time
class GUI(object):
"""GUI Object"""
def __init__(self):
self.root = tk.Tk()
self.root.title("Window")
self.root.status_lbl = tk.Label(self.root, text = "Label", width = 30)
self.root.status_lbl.grid(row = 0, column = 0)
self.root.start = tk.Button(self.root, text = "Start", width = 30, command = self.doing_things)
self.root.start.grid(row = 1, column = 0)
self.root.stop = tk.Button(self.root, text = "Stop", width = 30, command = None)
self.root.stop.grid(row = 2, column = 0)
self.root.mainloop()
def doing_things(self):
self.root.start.config(state = 'disabled')
Other_thread = threading.Thread(None, Other)
Other_thread.start()
class Other(object):
"""Something Else"""
def __init__(self):
self.msg2 = "Other Thread"
self.doing_things()
def doing_things(self):
count = 0
while 1 == 1:
count += 1
data = (self.msg2 + " " + str(count))
print(data)
time.sleep(1)
GUI_thread = threading.Thread(None, GUI)
GUI_thread.start()
任何幫助將是巨大的,這是推動我瘋了。
UPDATE:
所以這個回答我的兩個問題,並確實不錯:
import tkinter as tk
import threading
import queue
import time
class GUI(object):
"""GUI Object"""
def __init__(self):
self.root = tk.Tk()
self.root.title("Window")
self.stop_flag = str
self.status = tk.StringVar()
self.status.set("plop")
self.root.status_lbl = tk.Label(self.root, textvariable=self.status, width = 30)
self.root.status_lbl.grid(row = 0, column = 0)
self.root.start = tk.Button(self.root, text = "Start", width = 30, command = self.doing_things)
self.root.start.grid(row = 1, column = 0)
self.root.stop = tk.Button(self.root, text = "Stop", width = 30, command = self.stop)
self.root.stop.grid(row = 2, column = 0)
self.root.mainloop()
def doing_things(self):
self.stop_flag = False
self.root.start.config(state = 'disabled')
Other_thread = threading.Thread(None, Other, args=(self,))
Other_thread.start()
def stop(self):
self.root.start.config(state = 'normal')
self.stop_flag = True
class Other(object):
"""Something Else"""
def __init__(self, gui):
self.count = 0
self.gui = gui
self.msg2 = "Other Thread"
self.doing_things()
def doing_things(self):
count = self.count
while not self.gui.stop_flag:
count += 1
data = (self.msg2 + " " + str(count))
print(data)
self.gui.status.set(data)
time.sleep(1)
GUI_thread = threading.Thread(None, GUI)
GUI_thread.start()
真的混淆我是自後需要逗號的唯一的事:
Other_thread = threading.Thread(None, Other, args=(self,))
這完美的工作,任何想法如何讓停止工作? – tgikal
沒關係,現在你指出瞭如何更改線程間的變量,我可以讓第二個線程的函數在while循環中運行,而不是基於第一個線程中設置的變量。 – tgikal