与 Tkinter 的串行通信 [英] Serial communication with Tkinter

查看:64
本文介绍了与 Tkinter 的串行通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Python 编写一些代码来制作控制电子板的 GUI.我在 GUI 上放置按钮并通过单击它来发送命令.这部分有效.但是我需要接收来自董事会的信息来更改 GUI 中的一些内容.这是我没有成功做到的部分.我在 this 中找到了一些提示问题,这允许我在没有 GUI 的情况下读取 COM 端口.当我尝试添加一个带有输入框的窗口并用传入的值刷新它时,我什么也没看到.
这是我的代码:

I'm writing some code in Python to make a GUI that controls an electronic board. I put buttons on the GUI and send commands by clicking on it. This part works. But I need to receive information that comes from the board to change some stuff in the GUI. It is this part that I don't succeed to do. I found some tips in this question, that allows me to read the COM port without the GUI. When I try to add a window with an entry box and refresh it with the incoming values i dont see anything.
Here is my code :

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()

当我运行它时,窗口没有打开,但其余工作正常.你对我有什么建议吗?

When I run it, the window doesn't open but the rest works fine. Do you have any tips for me?

推荐答案

实际上我成功地做了一个脚本,它读取我发送的内容并允许我在按下按钮时写一个链从串行导入 *从 Tkinter 导入 *

Actually I succeeded in doing a script that reads what I send and allow me to write a chain when I push a button from serial import * from 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()

这篇关于与 Tkinter 的串行通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆