Reputation: 31
I am trying to get a Python GUI window using Tkinter to continuously display data streaming from an Arduino Uno board acting as a voltmeter. With the code I've got, the window will display one data point, and once the window gets closed, a new window opens up with the next available data point. Here's the code I've been using:
import serial
from Tkinter import *
ser = serial.Serial('/dev/tty.usbmodem621')
ser.baudrate = 9600
while 1 == 1:
reading = ser.readline()
root = Tk()
w = Label(root, text = reading)
w.pack()
root.mainloop()
I'm using a MacBook Pro, and the pySerial package for my serial communications. How do I get the window to refresh itself?
Upvotes: 3
Views: 2979
Reputation: 276
I think the problem is that you're creating a new root for every loop iteration. Try this code:
import serial
from Tkinter import *
from time import sleep
ser = serial.Serial('/dev/tty.usbmodem621')
ser.baudrate = 9600
def update():
while 1:
reading.set(ser.readline())
root.update()
sleep(1)
root=Tk()
reading = StringVar()
w = Label(root, textvariable = reading)
w.pack()
root.after(1,update)
root.mainloop()
This sets up the "mainloop" to call the "update" function after a millisecond and uses a reference to the variable "reading" rather that the actual value of it, allowing it to be updated.
I hope this helps.
Upvotes: 2