經過多年的閱讀,這是我第一篇文章Stack Overflow。通過過程中的方法更新TKInter標籤
我正在寫一個Python程序並用TKInter構建一個前端。我的課堂上有一個名爲label_cpu的標籤。我的希望是,我可以在進程中使用方法cpu_counter來更新當前CPU使用時間的標籤。如果我把一個實例的方法,說GUI.cpu_counter()標籤的更新,但是當我試圖通過的Process.Start(啓動方法)談到了以下消息:
Traceback (most recent call last):
File "C:/Users/Chris Local/OneDrive/Github/python/gui2.py", line 51, in <module>
p.start()
File "C:\Python35\lib\multiprocessing\process.py", line 105, in start
self._popen = self._Popen(self)
File "C:\Python35\lib\multiprocessing\context.py", line 212, in _Popen
return _default_context.get_context().Process._Popen(process_obj)
File "C:\Python35\lib\multiprocessing\context.py", line 313, in _Popen
return Popen(process_obj)
File "C:\Python35\lib\multiprocessing\popen_spawn_win32.py", line 66, in __init__
reduction.dump(process_obj, to_child)
File "C:\Python35\lib\multiprocessing\reduction.py", line 59, in dump
ForkingPickler(file, protocol).dump(obj)
_pickle.PicklingError: Can't pickle <class '_tkinter.tkapp'>: attribute lookup tkapp on _tkinter failed
Process finished with exit code 1
這裏的驗證碼:
from tkinter import *
import thread
import sys
import os
from multiprocessing import Process
from tkinter import Tk, Checkbutton, Label
from tkinter import StringVar, IntVar
class MainMenu:
def __init__(self, master):
frame = Frame(master)
frame.pack()
# Configure label for CPU counter/thread
self.m = StringVar()
self.m.set("CPU COUNTER GOES HERE")
self.label_cpu = Label(frame, textvariable = self.m)
self.button1 = Button(frame, text = "1. Enter Provinces (from Scratch)")
self.label_cpu.grid(row=1, sticky = W)
self.button1.grid(row=2, sticky = W)
def cpu_counter(self):
while (1 > 0):
v = str(os.times())
print(v)
self.m.set(v)
def cpu_counter_external(GUI):
#I tried tricking out the process.start() by aiming it here, but
#this doesn't work if launched in a process either.
GUI.cpu_counter()
if __name__ == '__main__':
root = Tk()
menubar = Menu(root)
menubar.option_add('*tearOff', FALSE)
submenu = Menu(menubar)
menubar.add_cascade(label = "File!", menu = submenu)
menubar.add_cascade(label = "Help!", menu = submenu)
root.config(menu=menubar)
GUI = MainMenu(root)
p = Process(target = GUI.cpu_counter)
#The following line, GUI.cpu_counter() updates the label
#but it should not be run unless in a process.
#GUI.cpu_counter()
p.start()
p.join()
root.mainloop()