我正在尝试制作一个 Python 串行端口侦听器应用程序。
我的问题是在后台运行侦听器功能而不杀死 GUI。
这是代码:
import sys
import getopt
import serial
from time import sleep
from threading import *
from Tkinter import *
import io
#ser = serial.serial_for_url('loop://', timeout=1)
#sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser))
runing = True
ser = None
class App:
global ser
def __init__(self, master):
varCOM = StringVar(master)
varCOM.set("COM1")
listbox = OptionMenu(master, varCOM, "COM1", "COM2", "COM3", "COM4")
listbox.grid(row=0, column=0)
varBaudRate = StringVar(master)
varBaudRate.set(4800)
listboxBaudrate = OptionMenu(master, varBaudRate, 300, 1200, 2400, 4800, 9600, 14400, 19200, 38400)
listboxBaudrate.grid(row=0, column=1)
varParity = StringVar(master)
varParity.set("None")
listboxParity = OptionMenu(master, varParity, "None", "Even", "ODD", "Mark", "Space")
listboxParity.grid(row=1, column=0)
varDataBits = StringVar(master)
varDataBits.set(8)
listboxDataBits = OptionMenu(master, varDataBits, 5, 6, 7, 8)
listboxDataBits.grid(row=1, column=1)
varStopBits = StringVar(master)
varStopBits.set(2)
listboxStopBits = OptionMenu(master, varStopBits, 1, 2)
listboxStopBits.grid(row=2, column=0)
def detener():
global runing
runing = False
detencion = Thread(target=detener)
def detencionRun():
detencion.run()
def write():
while runing == True:
#sleep(10)
line = ser.read(14)
if line:
print line
file.write(line)
itinerancia = Thread(target=write)
def openPort(port='COM1', baudrate=1920, bytesize=8, parity='N', stopbits=1):
try:
global ser
global file
port = varCOM.get()
baudrate = int(varBaudRate.get())
bytesize = int(varDataBits.get())
stopbits = int(varStopBits.get())
ser = serial.Serial(port=port, baudrate=baudrate, bytesize=bytesize, parity=parity, stopbits=stopbits)
file = open("lecture.txt", "a")
file.write("-- INICIO PROGRAMA --\n")
itinerancia.run()
#while runing == True:
# line = ser.read(14)
# if line:
# print line
# file.write(line)
file.write("\n-- FIN DEL PROGRAMA --\n")
file.close()
except serial.SerialException:
print 'No se pudo abrir el puerto'
return
def ejecutar():
detener = Button(master, text="Detener", command=detencionRun)
detener.grid(row=3, column=0)
t = Thread(target=openPort)
t.run()
ejecutar = Button(master, text="Ejecutar", command=ejecutar)
ejecutar.grid(row=3, column=1)
if __name__ == '__main__':
root = Tk()
app = App(root)
root.mainloop()
应用程序在 while 循环中冻结。 抱歉我的英语和编码不好(我是 Python 新手)