[英]Closing my tkinter serial app, gives me an exception
我有這個程序可以從串行中獲取數據並將它們顯示在 tkinter 框架上。
這是代碼:
import tkinter as tk
import tkinter.ttk as ttk
import serial.tools.list_ports
from tkinter import scrolledtext
#new stuff from vid
import time
import serial
import threading
import continuous_threading
#to be used on our canvas
HEIGHT = 700
WIDTH = 800
#hardcoded baud rate
baudRate = 9600
ser = serial.Serial('COM16', baudRate)
val1 = 0
index = []
def readSerial():
global val1
ser_bytes = ser.readline()
ser_bytes = ser_bytes.decode("utf-8")
val1 = ser_bytes
scrollbar.insert("end", val1)
t1 = continuous_threading.PeriodicThread(0.1, readSerial)
#----------------------------------------------------------------------
# --- functions ---
#the following two functtions are for the seria port selection, on frame 1
def serial_ports():
return serial.tools.list_ports.comports()
def on_select(event=None):
global COMPort
COMPort = cb.get()
print(COMPort)
# --- functions ---
#--------------------------------------------------------------------------------------------------------------
# --- main ---
root = tk.Tk() #here we create our tkinter window
root.title("Sensor Interface")
#we use canvas as a placeholder, to get our initial screen size (we have defined HEIGHT and WIDTH)
canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()
#we use frames to organize all the widgets in the screen
# --- frame 1 ---
frame1 = tk.Frame(root)
frame1.place(relx=0, rely=0.05, relheight=0.03, relwidth=1, anchor='nw') #we use relheight and relwidth to fill whatever the parent is - in this case- root
label0 = tk.Label(frame1, text="Select the COM port that the device is plugged in: ")
label0.config(font=("TkDefaultFont", 8))
label0.place(relx = 0.1, rely=0.3, relwidth=0.3, relheight=0.5)
cb = ttk.Combobox(frame1, values=serial_ports())
cb.place(relx=0.5, rely=0.5, anchor='center')
# assign function to cmbobox
cb.bind('<<ComboboxSelected>>', on_select)
# --- frame 1 ---
# --- frame 2 ---
frame2 = tk.Frame(root, bg='#80c1ff') #remove color later
frame2.place(relx=0, rely=0.1, relheight=1, relwidth=1, anchor='nw')
# make a scrollbar
scrollbar = scrolledtext.ScrolledText(frame2)
scrollbar.place(relx=0, rely=0, relheight=1, relwidth=1, anchor='nw')
# --- frame 2 ---
#--------------------------------------------------------------------------------------------------------
t1.start()
root.mainloop() #here we run our app
當我終止生成的 GUI 時,我在終端上得到這個異常:
Exception in thread Thread-1:
Fatal Python error: could not acquire lock for <_io.BufferedWriter name='<stderr
>'> at interpreter shutdown, possibly due to daemon threads
Python runtime state: finalizing (tstate=005C8F38)
Thread 0x00001a30 (most recent call first):
File "C:\Users\User1\AppData\Local\Programs\Python\Python38-32\lib\threading.p
y", line 1202 in invoke_excepthook
File "C:\Users\User1\AppData\Local\Programs\Python\Python38-32\lib\threading.p
y", line 934 in _bootstrap_inner
File "C:\Users\User1\AppData\Local\Programs\Python\Python38-32\lib\threading.p
y", line 890 in _bootstrap
Current thread 0x00001918 (most recent call first):
<no Python frame>
當我用 control+C 從終端終止它時,我得到:
Traceback (most recent call last):
File "mySerial.py", line 110, in <module>
root.mainloop() #here we run our app
File "C:\Users\User1\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__i
nit__.py", line 1420, in mainloop
self.tk.mainloop(n)
KeyboardInterrupt
Exception in thread Thread-1:
Fatal Python error: could not acquire lock for <_io.BufferedWriter name='<stderr
>'> at interpreter shutdown, possibly due to daemon threads
Python runtime state: finalizing (tstate=00578F38)
Thread 0x00001ad0 (most recent call first):
File "C:\Users\User1\AppData\Local\Programs\Python\Python38-32\lib\threading.p
y", line 1202 in invoke_excepthook
File "C:\Users\User1\AppData\Local\Programs\Python\Python38-32\lib\threading.p
y", line 934 in _bootstrap_inner
File "C:\Users\User1\AppData\Local\Programs\Python\Python38-32\lib\threading.p
y", line 890 in _bootstrap
Current thread 0x000013d8 (most recent call first):
<no Python frame>
為什么會這樣?
編輯:這是我的代碼和錯誤消息,嘗試 AST 的建議:
import tkinter as tk
import tkinter.ttk as ttk
import serial.tools.list_ports
from tkinter import scrolledtext
import time
import serial
import threading
import continuous_threading
#to be used on our canvas
HEIGHT = 700
WIDTH = 800
#hardcoded baud rate
baudRate = 9600
# flag to be notified when application is terminated
stop=False
ser = serial.Serial('COM16', baudRate)
val1 = 0
def readSerial():
global val1, stop
if not stop:
ser_bytes = ser.readline()
ser_bytes = ser_bytes.decode("utf-8")
val1 = ser_bytes
scrollbar.insert("end", val1)
else:
return
t1 = continuous_threading.PeriodicThread(0.1, readSerial)
#----------------------------------------------------------------------
# --- functions ---
#the following two functions are for the seria port selection, on frame 1
def serial_ports():
return serial.tools.list_ports.comports()
def on_select(event=None):
global COMPort
COMPort = cb.get()
print(COMPort)
def on_close():
global stop
stop=True
root.destroy()
# --- functions ---
#--------------------------------------------------------------------------------
# --- main ---
root = tk.Tk() #here we create our tkinter window
root.title("Sensor Interface")
root.protocol('WM_DELETE_WINDOW', on_close)
#we use canvas as a placeholder, to get our initial screen size (we have defined HEIGHT and WIDTH)
canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()
#we use frames to organize all the widgets in the screen
# --- frame 1 ---
frame1 = tk.Frame(root)
frame1.place(relx=0, rely=0.05, relheight=0.03, relwidth=1, anchor='nw') #we use relheight and relwidth to fill whatever the parent is - in this case- root
label0 = tk.Label(frame1, text="Select the COM port that the device is plugged in: ")
label0.config(font=("TkDefaultFont", 8))
label0.place(relx = 0.1, rely=0.3, relwidth=0.3, relheight=0.5)
cb = ttk.Combobox(frame1, values=serial_ports())
cb.place(relx=0.5, rely=0.5, anchor='center')
# assign function to cmbobox
cb.bind('<<ComboboxSelected>>', on_select)
# --- frame 1 ---
# --- frame 2 ---
frame2 = tk.Frame(root, bg='#80c1ff') #remove color later
frame2.place(relx=0, rely=0.1, relheight=1, relwidth=1, anchor='nw')
# make a scrollbar
scrollbar = scrolledtext.ScrolledText(frame2)
scrollbar.place(relx=0, rely=0, relheight=1, relwidth=1, anchor='nw')
# --- frame 2 ---
#--------------------------------------------------------------------------------
t1.start()
root.mainloop() #here we run our app
我得到的錯誤是我列為代碼的第一個錯誤。
編輯2:當我做AST的第二種方法時:
如果我關閉 GUI(按 X),它會在沒有任何錯誤的情況下關閉,但提示卡在終端上 - 我無法輸入任何內容,甚至鍵盤退出 (Control+C) 也不起作用。
如果程序運行並且我在終端中使用鍵盤退出(Control+C)退出,我會收到鍵盤中斷錯誤(我已列為代碼的第二個錯誤)
據我說,這是因為可能有一個計划線程在應用程序被銷毀后執行,因此無法找到它必須更新的 GUI 元素。
我沒有嘗試運行您的代碼,但我認為這可能會有所幫助
將 window 刪除與更新標志的 function 相關聯( stop
)
def on_close():
global stop
stop=True
root.destroy()
root.protocol('WM_DELETE_WINDOW', on_close)
stop=False
並修改readSerial
function 以檢查是否相同
def readSerial():
global val1,stop
if not stop:
ser_bytes = ser.readline()
ser_bytes = ser_bytes.decode("utf-8")
val1 = ser_bytes
scrollbar.insert("end", val1)
else:
return
編輯
這是threading.py
中的 function 引發異常。
def _bootstrap(self):
# Wrapper around the real bootstrap code that ignores
# exceptions during interpreter cleanup. Those typically
# happen when a daemon thread wakes up at an unfortunate
# moment, finds the world around it destroyed, and raises some
# random exception *** while trying to report the exception in
# _bootstrap_inner() below ***. Those random exceptions
# don't help anybody, and they confuse users, so we suppress
# them. We suppress them only when it appears that the world
# indeed has already been destroyed, so that exceptions in
# _bootstrap_inner() during normal business hours are properly
# reported. Also, we only suppress them for daemonic threads;
# if a non-daemonic encounters this, something else is wrong.
try:
self._bootstrap_inner()
except:
if self._daemonic and _sys is None:
return
raise
在這種情況下,可以在所有non-daemonic
線程都被殺死時殺死線程,您可以嘗試將線程設置為daemonic
線程,以便自動處理異常。 我認為這種方法不需要標志。
t1.daemon=True
t1.start()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.