在我的代码中,我希望将序列数据接收到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()
答案 0 :(得分:0)
您可以使用label["text"]
设置/获取Tkinter标签的内容。
使用此代码段:
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()定义在哪里?