如何在python中将串行数据打印到标签中?
Posted
技术标签:
【中文标题】如何在python中将串行数据打印到标签中?【英文标题】:How to print serial data into label in python? 【发布时间】:2017-07-15 06:47:19 【问题描述】:在我的代码中,我想将串行数据接收到data
,并想打印到标签上。并想通过按钮和选择器发送开/关命令。除了将data
打印到标签中外,一切都很好。下一步是什么?
import serial
import Tkinter
from Tkinter import *
win = Tk()
ser = serial.Serial('com8',9600)
def bt1 (): ser.write('on')
def bt2 (): ser.write('off')
def bt3 (): ser.write(v.get())
def makewindow ():
global v,d
frame1 = Frame(win)
frame1.pack(side = LEFT)
b1 = Button(frame1, text = "ON", command = bt1)
b2 = Button(frame1, text = "OFF", command = bt2)
b1.grid(row = 0, column = 0)
b2.grid(row = 0, column = 1)
frame2 = Frame(win)
frame2.pack()
v = StringVar()
r1 = Radiobutton(frame2,text = 'on', variable = v, value = 'on')
r2 = Radiobutton(frame2,text = 'off', variable = v, value = 'off')
r1.select()
b3 = Button(frame2, text = 'send', command = bt4)
b3.pack(sid = RIGHT, padx = 5)
r1.pack(side = LEFT)
r2.pack(side = LEFT)
frame3 = Frame(win)
frame3.pack()
d = StringVar()
d.set('default')
label = Label(frame3, textvariable = d, relief = RAISED)
label.pack(side = RIGHT)
return win
def update():
data = ser.readline(ser.inWaiting())
win.after(100,update)
update()
win = makewindow()
win.mainloop()
【问题讨论】:
您能更详细地说明您的问题吗?执行有什么问题? 【参考方案1】:您可以使用label["text"]
设置/获取 Tkinter 标签的内容。
使用这个sn-p:
def update():
global d
data = ser.readline(ser.inWaiting())
d.set(data)
请不要使用全局变量。他们是非常糟糕的做法。相反,您应该将程序包装到一个类中:
import serial
import Tkinter
from Tkinter import *
class SerialViewer:
def __init__(self):
self.win = Tk()
self.ser = serial.Serial('com8',9600)
def bt1 (self):
self.ser.write('on')
def bt2 (self):
self.ser.write('off')
def bt3 (self):
self.ser.write(self.v.get())
def makewindow (self):
frame1 = Frame(self.win)
frame1.pack(side = LEFT)
b1 = Button(frame1, text = "ON", command = self.bt1)
b2 = Button(frame1, text = "OFF", command = self.bt2)
b1.grid(row = 0, column = 0)
b2.grid(row = 0, column = 1)
frame2 = Frame(self.win)
frame2.pack()
self.v = StringVar()
r1 = Radiobutton(frame2,text = 'on', variable = self.v, value = 'on')
r2 = Radiobutton(frame2,text = 'off', variable = self.v, value = 'off')
r1.select()
b3 = Button(frame2, text = 'send', command = self.bt4)
b3.pack(sid = RIGHT, padx = 5)
r1.pack(side = LEFT)
r2.pack(side = LEFT)
frame3 = Frame(self.win)
frame3.pack()
self.d = StringVar()
self.d.set('default')
label = Label(frame3, textvariable = self.d, relief = RAISED)
label.pack(side = RIGHT)
def update(self):
data = self.ser.readline(self.ser.inWaiting())
self.d.set(data)
self.win.after(100,self.update)
def run(self):
self.makewindow()
self.update()
self.win.mainloop()
SerialViewer().run()
现在应该可以工作了,虽然我无法测试它。但是 bt4() 是在哪里定义的呢?
【讨论】:
实际上 bt4() 将是 bt3() 非常感谢?以上是关于如何在python中将串行数据打印到标签中?的主要内容,如果未能解决你的问题,请参考以下文章
如何在从串口python pyqt接收的textbrowser pyqt5上附加串行数据[重复]