3

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It helped quite a bit, thanks. The only thing that needed to be done differently was to define the variable 'reading' so I did that after defining 'update' and the code works exactly how I was expecting it to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.