Tkinter unable to get updated a StringVar

99 views Asked by At

I am reading serial info and want to pass it to the GUI in Tkinter . This code is working, but when I want to use canvas(because I will do a dashboard type GUI), I do not get any print out on the GUI.

if __name__ == '__main__':
    pass

import serial
from tkinter import *
import tkinter as tk
import tkinter.font as tkf

ser = serial.Serial('COM2')
ser.baudrate = 9600

def update():
    c = StringVar()
    c=ser.readline()
    theta.set(c)  
    root.after(100,update)

root=Tk()
root.title("viento")
theta = StringVar()

w = Label(root, textvariable = theta, font ="Times 16 bold", fg="red")
w.pack()

root.after(100,update)    
root.mainloop()

As soon as I change the label statement with

w=Canvas(root,width = 200, height= 100)
w.pack()
w.create_text(100,50,text=theta.get())

I get an empty GUI . What is wrong ?

2

There are 2 answers

0
tobias_k On

As far as I know, you can not use a StringVar for setting the text displayed on a Canvas. You can, however, get the ID of the text created on the canvas and re-configure it afterwards.

Something like this:

def update():
    w.itemconfigure(text_id, text=ser.readline())
    root.after(100, update)

w = Canvas(root, width=200, height=100)
w.pack()
text_id = w.create_text(100, 50, text="")
1
Martin On

thanks for your help. Jonrsharpe were right.Create text executed just once, so combing that comment with Tobias, moved that statement w.create_text(100,50,text=theta.get()) to the update function and then I got what I was expecting. The only minor comment is that the values were overwritten one over the following.Not sure why . It seems like the new updated value did not clear the previous one and in the GUI after a few samples the values were impossible to read. For me really minor, since I was able to fix the problem and designed my Canvas GUI ,that is now up and running .