【发布时间】:2015-01-27 08:27:45
【问题描述】:
我正在用 Python 编写一些代码来制作一个控制电子板的 GUI。
我将按钮放在 GUI 上并通过单击它来发送命令。这部分有效。
但我需要接收来自开发板的信息来更改 GUI 中的一些内容。这是我没有成功完成的部分。
我在this question 中找到了一些提示,可以让我在没有 GUI 的情况下读取 COM 端口。当我尝试添加一个带有输入框的窗口并用传入的值刷新它时,我什么也没看到。
这是我的代码:
import serial
import threading
from time import sleep
from Tkinter import*
import sys
wind=Tk()
global var
var=StringVar(wind)
var.set("value 1")
entry_COM=Entry(wind,textvariable=var)
entry_COM.place(x=0,y=0,width=100,height=50)
ser = serial.Serial(port='COM1',baudrate=115200,parity=serial.PARITY_NONE,stopbits=serial.STOPBITS_ONE,bytesize=serial.EIGHTBITS,timeout=0)
global thread
thread= None
stop_task = threading.Event()
def do_task():
global var
var.set("value 2")
for i in xrange(1):
if stop_task.is_set():
break
print(i)
sleep(1)
while True:
byte = ser.read(1) # No need for a loop here, read(1) returns a length 1 string
character = byte # I'm not familiar with the serial module, but I think this isn't needed
if character == 'S':
# We check that we are not executing the task already, and if so we handle it accordingly
if thread:
print('Error: a task is already running!')
continue
# Start the task in a thread
stop_task.clear()
thread = threading.Thread(target=do_task)
thread.start()
elif character == 'K':
print('K received -> BREAK FROM TASK')
if thread:
stop_task.set()
thread = None
elif character == 'E':
ser.close()
print "closed"
try:
wind.destroy()
except:
pass
sys.exit()
wind.mainloop()
当我运行它时,窗口没有打开,但其余的工作正常。 你有什么建议给我吗?
【问题讨论】:
标签: python user-interface tkinter serial-port