与Tkinter串行通信

时间:2015-01-27 08:27:46

标签: python user-interface tkinter serial-port

我正在用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()

当我运行它时,窗口没有打开,但其余的工作正常。 你有什么提示吗?

2 个答案:

答案 0 :(得分:0)

实际上我成功地创建了一个脚本来读取我发送的内容并允许我在按下按钮时编写链 来自串口进口* 来自Tkinter import *

class serial_test(object):
    def __init__(self):
        self.serialPort = "COM1"
        self.baudRate = 9600
        self.ser = Serial(self.serialPort , self.baudRate, timeout=0, writeTimeout=0) #ensure non-blocking
        #make a TkInter Window
        self.root = Tk()
        self.root.wm_title("Reading Serial")      
        # make a scrollbar
        self.scrollbar = Scrollbar(self.root)
        self.scrollbar.pack(side=RIGHT, fill=Y)       
        # make a text box to put the serial output
        self.log = Text ( self.root, width=30, height=30, takefocus=0)
        self.log.pack()       
        # attach text box to scrollbar
        self.log.config(yscrollcommand=self.scrollbar.set)
        self.scrollbar.config(command=self.log.yview)
        #make our own buffer
        self.buff=0
        self.bou=Button(self.root,text='Valid',command=self.writeSerial)
        self.bou.pack()
        self.root.after(100, self.readSerial)        
        self.root.protocol("WM_DELETE_WINDOW", self.Intercept)
        self.root.mainloop()
    def Intercept(self):
        try : 
            self.ser.close()
        except:
            pass
        self.root.destroy()
    def writeSerial(self):
        self.ser.write("Testing")

    def readSerial(self):
        while True:
            self.c = self.ser.read() # attempt to read a character from Serial
            #was anything read?
            if len(self.c) == 0:
                break
            # get the buffer from outside of this function
            self.log.insert(END, self.c)
            self.buff=self.buff+1
            if self.c == '\r':
                for i in range(30-self.buff):
                    self.log.insert(END, ' ')
                    self.buff=0

            if self.buff==30:
                self.buff=0
        self.root.after(10, self.readSerial) # check serial again soon
serial_test()

答案 1 :(得分:-2)

import serial
from tkinter import *
class serial_test(object):
    def __init__(self):
        self.serialPort = "COM5"
        self.baudRate = 9600
        self.ser = serial.Serial(self.serialPort , self.baudRate, timeout=0, writeTimeout=0) #ensure non-blocking
        #make a TkInter Window
        self.root = Tk()
        self.root.wm_title("Reading Serial")
        # make a scrollbar
        self.scrollbar = Scrollbar(self.root)
        self.scrollbar.pack(side=RIGHT, fill=Y)
        # make a text box to put the serial output
        self.log = Text ( self.root, width=30, height=30, takefocus=0)
        self.log.pack()
        # attach text box to scrollbar
        self.log.config(yscrollcommand=self.scrollbar.set)
        self.scrollbar.config(command=self.log.yview)
        #make our own buffer
        self.buff=0
        self.bou=Button(self.root,text='Valid',command=self.writeSerial)
        self.bou.pack()
        self.root.after(100, self.readSerial)
        self.root.protocol("WM_DELETE_WINDOW", self.Intercept)
        self.root.mainloop()
    def Intercept(self):
        try :
            self.ser.close()
        except:
            pass
        self.root.destroy()
    def writeSerial(self):
        self.ser.write("Testing")

    def readSerial(self):
        while True:
            self.c = self.ser.read() # attempt to read a character from Serial
            #was anything read?
            if len(self.c) == 0:
                break
            # get the buffer from outside of this function
            self.log.insert(END, self.c)
            self.buff=self.buff+1
            if self.c == '\r':
                for i in range(30-self.buff):
                    self.log.insert(END, ' ')
                    self.buff=0

            if self.buff==30:
                self.buff=0
        self.root.after(10, self.readSerial) # check serial again soon
a=serial_test()
a.readSerial()