Python 如何根据来自单独线程的特定值更新小部件?
我的GUI应用程序有多个屏幕(3),而每个屏幕都包含用户可以更改的特定文本小部件(我根据一个众所周知的stackoverflow解决方案基于此多屏幕GUI)。在填充某个屏幕的字段后,用户可以将这些值“烧录”到某个硬件。为了能够“刻录”到硬件,我在应用程序运行后立即启动到硬件的Telnet会话(IP是硬编码的) 每个框架都显示了状态栏,我想用与硬件的Telnet连接的当前状态来更新状态栏。为了维护Telnet连接,我使用了一个单独的线程。我还使用了一个队列来更新当前状态 当Telnet会话状态更改时,我可以通过简单的打印到控制台进行更新。如果Telnet会话因任何好(或坏)原因断开连接,我也能够恢复该会话 我的问题是无法用当前状态更新状态栏(状态标签)。在下面的代码中,您可以看到我试图在状态更改时生成一个事件。但是,它没有起作用。如何用实际状态更新状态栏 编辑后 (我做了很大的努力,删除了200多行代码):Python 如何根据来自单独线程的特定值更新小部件?,python,python-3.x,tkinter,python-multithreading,Python,Python 3.x,Tkinter,Python Multithreading,我的GUI应用程序有多个屏幕(3),而每个屏幕都包含用户可以更改的特定文本小部件(我根据一个众所周知的stackoverflow解决方案基于此多屏幕GUI)。在填充某个屏幕的字段后,用户可以将这些值“烧录”到某个硬件。为了能够“刻录”到硬件,我在应用程序运行后立即启动到硬件的Telnet会话(IP是硬编码的) 每个框架都显示了状态栏,我想用与硬件的Telnet连接的当前状态来更新状态栏。为了维护Telnet连接,我使用了一个单独的线程。我还使用了一个队列来更新当前状态 当Telnet会话状态更改
从tkinter导入字体,ttk
将tkinter作为tk导入
从重新导入匹配
导入telnetlib
导入线程
导入队列
导入时间
大字体=(“Verdana”,12)
当前PN='123456789'#此全局版本用于自动PN填充
主机='10.0.1.235'
端口=23
telnet_session=None#创建telnet会话后,我将跟踪此变量
已连接=错误
燃烧等级PP(tk.tk):
定义初始化(self,*args,**kwargs):
tk.tk.\uuuuu初始化(self,*args,**kwargs)
容器=tk.框架(自身)
container.pack(side=“top”,fill=“both”,expand=True)
container.grid_rowconfigure(0,权重=1)
container.grid\u column配置(0,权重=1)
self.title('Burning App')#处理应用程序的窗口标题
w=1000#窗宽
h=600#窗户高度
ws=self.winfo_screenwidth()#屏幕分辨率宽度
hs=self.winfo_屏幕高度()#屏幕分辨率高度
#w=ws*0.8#将GUI宽度调整到屏幕的80%
#h=hs*0.8#将GUI高度调整到屏幕的80%
x=(ws/2)-(w/2)#x坐标用于GUI布局
y=(hs/2)-(h/2)#X坐标,用于GUI放置
可自行调整大小(宽度=假,高度=假)
自身几何体(“%dx%d+%d+%d%”(w,h,x,y))
self.frames={}
对于F in(主屏幕、第一屏幕、第二屏幕):
框架=F(容器,自身)
self.frames[F]=帧
frame.grid(行=0,列=0,sticky=“nsew”)
自我显示框架(主屏幕)
#启动Telnet会话
self.connect_to_uut()
#创建将保存状态的队列
self.status_queue=queue.queue()
#设置线程以执行异步I/O
self.running=1#真
self.thread=threading.thread(target=self.workerThread)
self.thread.start()
#在GUI中启动定期调用,检查队列是否包含
#任何事
self.periodicCall()
def显示画面(自身,续):
'''
此功能用于根据需要提升机架
'''
帧=自身帧[续]
frame.tkraise()
def connect_to_uut(自我,重试=5):
'''
此函数用于连接到UUT
'''
全球telnet_会话
全球联网
对于范围内的(重试):
尝试:
telnet_session=telnetlib.telnet(主机、端口、超时=5)
已连接=真
self.event_generate(“”)
打破
除:
已连接=错误
self.event_generate(“”)
持续
def周期呼叫(自我):
"""
每10秒检查一次队列中是否有新内容。
这实际上是Telnet连接状态检查
"""
self.processIncoming()
如果不是自动运行:
#这是系统的野蛮停止。你可能想做什么
#在实际关闭之前进行一些清理。
导入系统
系统出口(1)
self.after(10000,self.periodicCall)
def processIncoming(自):
"""
处理队列中当前的所有消息(如果有)。
"""
#全球联网
而self.status_queue.qsize():
尝试:
msg=self.status\u queue.get(0)
#检查消息的内容并按它说的做
#作为测试,我只是简单地打印它
打印(msg)
#如果未连接:
#self.connect_to_uut()
队列除外。空:
通过
def workerThread(自):
"""
这就是我们处理异步I/O的地方。
"""
全球telnet_会话
全球联网
自运行时:
时间。睡眠(5)
尝试:
telnet_session.sock.send(telnetlib.IAC+telnetlib.NOP)
已连接=真
msg='已连接'
除:
已连接=错误
msg='Disconnected'#Telnet会话的实际状态
self.event_generate(“”)
如果未连接:
self.connect_to_uut()
self.status\u queue.put(msg)
类主屏幕(传统框架):
定义初始化(自、父、控制器):
tk.Frame.\uuuu init\uuuuu(自,父)
from tkinter import font, ttk
import tkinter as tk
from re import match
import telnetlib
import threading
import queue
import time
LARGE_FONT= ("Verdana", 12)
Current_PN = '123456789' # This global ver is used for the purpose of automatic PN fill
HOST = '10.0.1.235'
PORT = 23
telnet_session = None # After I create the Telnet session I will keep track with this variable
connected = False
class BurningApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side="top", fill="both", expand = True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.title('Burning App') #handling the application's Window title
w = 1000 # Windows width
h = 600 # Windows height
ws = self.winfo_screenwidth() # Screen resolution width
hs = self.winfo_screenheight() # Screen resolution height
# w = ws * 0.8 # Fit the GUI width to 80% percent of the screen
# h = hs * 0.8 # Fit the GUI height to 80% percent of the screen
x = (ws/2) - (w/2) # X coordinate for the purpose of GUI placement
y = (hs/2) - (h/2) # X coordinate for the purpose of GUI placement
self.resizable(width=False, height=False)
self.geometry('%dx%d+%d+%d'%(w,h,x,y))
self.frames = {}
for F in (MainScreen, FirstScreen, SecondScreen):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(MainScreen)
# Start the Telnet session
self.connect_to_uut()
# Create the queue that will hold the status
self.status_queue = queue.Queue()
# Set up the thread to do asynchronous I/O
self.running = 1 # True
self.thread = threading.Thread(target=self.workerThread)
self.thread.start()
# Start the periodic call in the GUI to check if the queue contains
# anything
self.periodicCall()
def show_frame(self, cont):
'''
This function is being used in order to raise a frame on demand
'''
frame = self.frames[cont]
frame.tkraise()
def connect_to_uut(self, Retry=5):
'''
This functions is used for the purpose of connecting to the UUT
'''
global telnet_session
global connected
for _ in range(Retry):
try:
telnet_session = telnetlib.Telnet(HOST, PORT, timeout=5)
connected = True
self.event_generate("<<StatusChange>>")
break
except:
connected = False
self.event_generate("<<StatusChange>>")
continue
def periodicCall(self):
"""
Check every 10 sec if there is something new in the queue.
This is actually Telnet connection status check
"""
self.processIncoming()
if not self.running:
# This is the brutal stop of the system. You may want to do
# some cleanup before actually shutting it down.
import sys
sys.exit(1)
self.after(10000, self.periodicCall)
def processIncoming(self):
"""
Handle all the messages currently in the queue (if any).
"""
# global connected
while self.status_queue.qsize():
try:
msg = self.status_queue.get(0)
# Check contents of message and do what it says
# As a test, I simply print it
print(msg)
# if not connected:
# self.connect_to_uut()
except queue.Empty:
pass
def workerThread(self):
"""
This is where we handle the asynchronous I/O.
"""
global telnet_session
global connected
while self.running:
time.sleep(5)
try:
telnet_session.sock.send(telnetlib.IAC + telnetlib.NOP)
connected = True
msg = 'Connected'
except:
connected = False
msg = 'Disconnected' #The Actual Status of the Telnet session
self.event_generate("<<StatusChange>>")
if not connected:
self.connect_to_uut()
self.status_queue.put(msg)
class MainScreen(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
self.Button_Font_Style1 = font.Font(family='Helvetica', size=30, weight='bold')
self.Status_BasicStyle = font.Font(family='Helvetica', size=10, weight='bold')
self.my_string_var = tk.StringVar()
self.button1 = tk.Button(self, text="PROGRAM 1",
command=lambda: controller.show_frame(FirstScreen),
width=30, font=self.Button_Font_Style1, bd=5)
self.button1.pack(pady=8)
self.button2 = tk.Button(self, text="PROGRAM 2",
command=lambda: controller.show_frame(FirstScreen),
width=30, font=self.Button_Font_Style1, bd=5)
self.button2.pack(pady=8)
self.button3 = tk.Button(self, text="PROGRAM 3",
command=lambda: controller.show_frame(FirstScreen),
width=30, font=self.Button_Font_Style1, bd=5)
self.button3.pack(pady=8)
self.button4 = tk.Button(self, text="PROGRAM 4",
command=lambda: controller.show_frame(SecondScreen),
width=30, font=self.Button_Font_Style1, bd=5)
self.button4.pack(pady=8)
self.button5 = tk.Button(self, text="PROGRAM FAN ",
command=lambda: controller.show_frame(FirstScreen),
width=30, font=self.Button_Font_Style1, bd=5)
self.button5.pack(pady=8)
self.status = tk.Label(self, textvariable=self.my_string_var, bd=2, relief=tk.SUNKEN, anchor=tk.W, font=self.Status_BasicStyle, fg="black")
self.my_string_var.set('Connecting...')
self.status.pack(side="bottom" , fill="x")
class FirstScreen(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
self.valid_string_color = "springgreen3"
self.invalid_string_color = "red2"
self.main_frame = tk.Frame(self)
self.Button_Font_Style1 = font.Font(family='Helvetica', size=20, weight='bold')
self.Lable_Font_Style1 = font.Font(family='Helvetica', size=20, weight='bold')
self.Status_BasicStyle = font.Font(family='Helvetica', size=10, weight='bold')
self.SN_Label = tk.Label(self.main_frame, text="Serial Number", font=self.Lable_Font_Style1)
self.SN_Label.grid(row=0, column=0, pady=10) # Y axis padding was added only to the label. This padding effects the whole line
self.SN_field = tk.Text(self.main_frame, height=1, width=30, font=self.Lable_Font_Style1)
self.SN_field.grid(row=0, column=1)
self.PN_Label = tk.Label(self.main_frame, text="Part Number", font=self.Lable_Font_Style1)
self.PN_Label.grid(row=1, column=0, pady=10) # Y axis padding was added only to the label. This padding effects the whole line
self.PN_field = tk.Text(self.main_frame, height=1, width=30, font=self.Lable_Font_Style1)
self.PN_field.grid(row=1, column=1)
self.HwVer_Label = tk.Label(self.main_frame, text="HW Version", font=self.Lable_Font_Style1)
self.HwVer_Label.grid(row=2, column=0, pady=10) # Y axis padding was added only to the label. This padding effects the whole line
self.HwVer_field = tk.Text(self.main_frame, height=1, width=30, font=self.Lable_Font_Style1)
self.HwVer_field.grid(row=2, column=1)
self.button2 = tk.Button(self.main_frame, text="Burn",
font=self.Button_Font_Style1, bd=5)
self.button2.grid(row=3, columnspan=2, pady=(20,0))
self.main_frame.pack()
self.my_string_var = tk.StringVar()
self.status = tk.Label(self, textvariable=self.my_string_var, bd=2, relief=tk.SUNKEN, anchor=tk.W, font=self.Status_BasicStyle, fg='black')
self.my_string_var.set('Connecting...')
self.status.pack(side="bottom" , fill="x")
self.status.bind("<<StatusChange>>", self.statuschange) # React to the status change event and change the status label accordingly
self.button1 = tk.Button(self, text="Main Menu",
command=lambda: controller.show_frame(MainScreen),
font=self.Button_Font_Style1, bd=5)
self.button1.pack(side="bottom", pady=(0,20))
def statuschange(self):
global connected
if connected:
self.my_string_var.set('Connected')
self.status.config(font=self.Status_ConnectedStyle, fg='springgreen3')
else:
self.my_string_var.set('Disonnected')
self.status.config(font=self.Status_DisconnectedStyle, fg='red2')
class SecondScreen(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
self.valid_string_color = "springgreen3"
self.invalid_string_color = "red2"
self.main_frame = tk.Frame(self)
self.Button_Font_Style1 = font.Font(family='Helvetica', size=20, weight='bold')
self.Lable_Font_Style1 = font.Font(family='Helvetica', size=20, weight='bold')
self.Status_BasicStyle = font.Font(family='Helvetica', size=5, weight='bold')
self.SN_Label = tk.Label(self.main_frame, text="Serial Number", font=self.Lable_Font_Style1)
self.SN_Label.grid(row=0, column=0, pady=10) # Y axis padding was added only to the label. This padding effects the whole line
self.SN_field = tk.Text(self.main_frame, height=1, width=30, font=self.Lable_Font_Style1)
self.SN_field.grid(row=0, column=1)
self.PN_Label = tk.Label(self.main_frame, text="Part Number", font=self.Lable_Font_Style1)
self.PN_Label.grid(row=1, column=0, pady=10) # Y axis padding was added only to the label. This padding effects the whole line
self.PN_field = tk.Text(self.main_frame, height=1, width=30, font=self.Lable_Font_Style1)
self.PN_field.grid(row=1, column=1)
self.HwVer_Label = tk.Label(self.main_frame, text="HW Version", font=self.Lable_Font_Style1)
self.HwVer_Label.grid(row=2, column=0, pady=10) # Y axis padding was added only to the label. This padding effects the whole line
self.HwVer_field = tk.Text(self.main_frame, height=1, width=30, font=self.Lable_Font_Style1)
self.HwVer_field.grid(row=2, column=1)
self.button2 = tk.Button(self.main_frame, text="Burn",
font=self.Button_Font_Style1, bd=5)
self.button2.grid(row=3, columnspan=2, pady=(20,0))
self.main_frame.pack()
self.my_string_var = tk.StringVar()
self.status = tk.Label(self, textvariable=self.my_string_var, bd=2, relief=tk.SUNKEN, anchor=tk.W, font=self.Status_BasicStyle, fg="black")
self.my_string_var.set('Connecting...')
self.status.pack(side="bottom" , fill="x")
self.status.bind("<<StatusChange>>", self.statuschange) # React to the status change event and change the status label accordingly
self.button1 = tk.Button(self, text="Main Menu",
command=lambda: controller.show_frame(MainScreen),
font=self.Button_Font_Style1, bd=5)
self.button1.pack(side="bottom", pady=(0,20))
def statuschange(self):
global connected
if connected:
self.my_string_var.set('Connected')
self.status.config(font=self.Status_ConnectedStyle, fg='springgreen3')
else:
self.my_string_var.set('Disonnected')
self.status.config(font=self.Status_DisconnectedStyle, fg='red2')
def main():
app = BurningApp()
app.mainloop()
if __name__ == '__main__':
main()
from tkinter import font, ttk
import tkinter as tk
from re import match
import telnetlib
import threading
import queue
import time
LARGE_FONT= ("Verdana", 12)
Current_PN = '123456789' # This global ver is used for the purpose of automatic PN fill
HOST = '10.0.1.235'
PORT = 23
telnet_session = None # After I create the Telnet session I will keep track with this variable
connected = False
class BurningApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side="top", fill="both", expand = True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.title('Burning App') #handling the application's Window title
w = 1000 # Windows width
h = 600 # Windows height
ws = self.winfo_screenwidth() # Screen resolution width
hs = self.winfo_screenheight() # Screen resolution height
# w = ws * 0.8 # Fit the GUI width to 80% percent of the screen
# h = hs * 0.8 # Fit the GUI height to 80% percent of the screen
x = (ws/2) - (w/2) # X coordinate for the purpose of GUI placement
y = (hs/2) - (h/2) # X coordinate for the purpose of GUI placement
self.resizable(width=False, height=False)
self.geometry('%dx%d+%d+%d'%(w,h,x,y))
self.frames = {}
for F in (MainScreen, FirstScreen, SecondScreen):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(MainScreen)
# Start the Telnet session
self.connect_to_uut()
# Create the queue that will hold the status
self.status_queue = queue.Queue()
# Set up the thread to do asynchronous I/O
self.running = 1 # True
self.thread = threading.Thread(target=self.workerThread)
self.thread.start()
# Start the periodic call in the GUI to check if the queue contains
# anything
self.periodicCall()
def show_frame(self, cont):
'''
This function is being used in order to raise a frame on demand
'''
frame = self.frames[cont]
frame.tkraise()
def connect_to_uut(self, Retry=5):
'''
This functions is used for the purpose of connecting to the UUT
'''
global telnet_session
global connected
for _ in range(Retry):
try:
telnet_session = telnetlib.Telnet(HOST, PORT, timeout=5)
connected = True
self.event_generate("<<StatusChange>>")
break
except:
connected = False
self.event_generate("<<StatusChange>>")
continue
def periodicCall(self):
"""
Check every 10 sec if there is something new in the queue.
This is actually Telnet connection status check
"""
self.processIncoming()
if not self.running:
# This is the brutal stop of the system. You may want to do
# some cleanup before actually shutting it down.
import sys
sys.exit(1)
self.after(10000, self.periodicCall)
def processIncoming(self):
"""
Handle all the messages currently in the queue (if any).
"""
# global connected
while self.status_queue.qsize():
try:
msg = self.status_queue.get(0)
# Check contents of message and do what it says
# As a test, I simply print it
print(msg)
# if not connected:
# self.connect_to_uut()
except queue.Empty:
pass
def workerThread(self):
"""
This is where we handle the asynchronous I/O.
"""
global telnet_session
global connected
while self.running:
time.sleep(5)
try:
telnet_session.sock.send(telnetlib.IAC + telnetlib.NOP)
connected = True
msg = 'Connected'
except:
connected = False
msg = 'Disconnected' #The Actual Status of the Telnet session
self.event_generate("<<StatusChange>>")
if not connected:
self.connect_to_uut()
self.status_queue.put(msg)
class MainScreen(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
self.Button_Font_Style1 = font.Font(family='Helvetica', size=30, weight='bold')
self.Status_BasicStyle = font.Font(family='Helvetica', size=10, weight='bold')
self.my_string_var = tk.StringVar()
self.button1 = tk.Button(self, text="PROGRAM 1",
command=lambda: controller.show_frame(FirstScreen),
width=30, font=self.Button_Font_Style1, bd=5)
self.button1.pack(pady=8)
self.button2 = tk.Button(self, text="PROGRAM 2",
command=lambda: controller.show_frame(FirstScreen),
width=30, font=self.Button_Font_Style1, bd=5)
self.button2.pack(pady=8)
self.status = tk.Label(self, textvariable=self.my_string_var, bd=2, relief=tk.SUNKEN, anchor=tk.W, font=self.Status_BasicStyle, fg="black")
self.my_string_var.set('Connecting...')
self.status.pack(side="bottom" , fill="x")
class FirstScreen(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
self.Button_Font_Style1 = font.Font(family='Helvetica', size=20, weight='bold')
self.Status_BasicStyle = font.Font(family='Helvetica', size=10, weight='bold')
self.my_string_var = tk.StringVar()
self.status = tk.Label(self, textvariable=self.my_string_var, bd=2, relief=tk.SUNKEN, anchor=tk.W, font=self.Status_BasicStyle, fg='black')
self.my_string_var.set('Connecting...')
self.status.pack(side="bottom" , fill="x")
self.status.bind("<<StatusChange>>", self.statuschange) # React to the status change event and change the status label accordingly
self.button1 = tk.Button(self, text="Main Menu",
command=lambda: controller.show_frame(MainScreen),
font=self.Button_Font_Style1, bd=5)
self.button1.pack(side="bottom", pady=(0,20))
def statuschange(self):
global connected
if connected:
self.my_string_var.set('Connected')
self.status.config(font=self.Status_ConnectedStyle, fg='springgreen3')
else:
self.my_string_var.set('Disonnected')
self.status.config(font=self.Status_DisconnectedStyle, fg='red2')
class SecondScreen(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
self.Button_Font_Style1 = font.Font(family='Helvetica', size=20, weight='bold')
self.Status_BasicStyle = font.Font(family='Helvetica', size=5, weight='bold')
self.my_string_var = tk.StringVar()
self.status = tk.Label(self, textvariable=self.my_string_var, bd=2, relief=tk.SUNKEN, anchor=tk.W, font=self.Status_BasicStyle, fg="black")
self.my_string_var.set('Connecting...')
self.status.pack(side="bottom" , fill="x")
self.status.bind("<<StatusChange>>", self.statuschange) # React to the status change event and change the status label accordingly
self.button1 = tk.Button(self, text="Main Menu",
command=lambda: controller.show_frame(MainScreen),
font=self.Button_Font_Style1, bd=5)
self.button1.pack(side="bottom", pady=(0,20))
def statuschange(self):
global connected
if connected:
self.my_string_var.set('Connected')
self.status.config(font=self.Status_ConnectedStyle, fg='springgreen3')
else:
self.my_string_var.set('Disonnected')
self.status.config(font=self.Status_DisconnectedStyle, fg='red2')
def main():
app = BurningApp()
app.mainloop()
if __name__ == '__main__':
main()
self.status.config(font=self.Status_ConnectedStyle,
text=self.my_string_var,fg='springgreen3')
def update_statusbar(self):
'''Poll the Telnet Session Status for the purpose of update'''
global connected
if connected:
self.my_string_var.set('Connected')
self.status.config(fg='springgreen3')
else:
self.my_string_var.set('Disconnected')
self.status.config(fg='red2')
self.after(2000, self.update_statusbar)