Getting Pyphons Tkinter to update a label with a changing variable [duplicate]

2024/10/7 16:19:44

I have a python script which I have written for a Raspberry Pi project, the script reads a value from a micrometer every second, and stores this value as a TkInter StringVar (http://effbot.org/tkinterbook/variable.htm)

What I want to happen is that that string is displayed on the UI as a label, and updated on the UI when the value changes.

I chose to use a Tkinter stringvar instead of a standard string because I thought that Tkinter would then automatically update on the UI, but it doesn't seem to work. Currently the script displays nothing for the label, and does not update when show sets virtual_reading.

From other threads I have read, the Tkinter method update_idletasks() should force the window to update, but I haven't been able to get this to work.

Can anyone give any guidance on where I'm going wrong? This is my first go at Python so sorry if this is simple.

import datetime
import csv
from tkinter import *
from tkinter import messagebox
import time
import pigpio
import osos.system("sudo pigpiod")root = Tk()winx = 480
winy = 320 CLOCK=21
DATA=20g_level=0
g_reading=0
g_bits=0pi = pigpio.pi()virtual_reading = StringVar()def go():global cb1global cb2cb1 = pi.callback(DATA, pigpio.EITHER_EDGE, cbf)cb2 = pi.callback(CLOCK, pigpio.EITHER_EDGE, cbf)root.after(1000 ,go)def show(bits, value):inch = value & (1<<23)minus = value & (1<<20)value = value & 0xfffffif inch:reading = value / 2000.0units = "in"else:reading = value / 100.0units = "mm"if minus:sign = "-"else:sign = ""global virtual_readingvirtual_reading = StringVar()virtual_reading.set("{} {:.3f} {}".format(sign, reading, units))print(virtual_reading.get())cb2.cancel()cb1.cancel()def measure(event=None):todays_date = datetime.date.today()  try:get_tool_no = int(tool_no_entry.get())if get_tool_no <= 0:messagebox.showerror("Try Again","Please Enter A Number")else:with open("thickness records.csv", "a") as thicknessdb: thicknessdbWriter = csv.writer(thicknessdb, dialect='excel', lineterminator='\r')thicknessdbWriter.writerow([get_tool_no] + [todays_date] + [virtual_reading.get()])thicknessdb.close()except:messagebox.showerror("Try Again","Please Enter A Number")tool_no_entry.delete(0, END)def cbf(g, l, t):global g_level, g_reading, g_bitsif g == DATA:if l == 0:g_level = 1else:g_level = 0elif g == CLOCK:if l == pigpio.TIMEOUT:if g_bits > 10:show(g_bits, g_reading)g_reading=0g_bits=0elif l == 0:g_reading = g_reading | (g_level<<g_bits)g_bits += 1go()record_button = Button(root,width = 30,height = 8,text='Measure',fg='black',bg="light grey", command = measure)tool_no_entry = Entry(root)reading_display = Label(root, font=("Helvetica", 22), text = virtual_reading.get())reading_display.place(x = 50, y =80)root.resizable(width=FALSE, height=FALSE) 
root.geometry('%dx%d' % (winx,winy)) 
root.title("Micrometer Reader V1.0")record_button.place(x = 340, y = 100, anchor = CENTER)tool_no_entry.place(x = 120, y = 250, anchor=CENTER)
tool_no_entry.focus_set()root.bind("<Return>", measure)root.mainloop()cb2.cancel()
cb1.cancel()
pi.stop()
Answer

You are misunderstanding how StringVars work. For one, you're recreating the StringVar every second, and only the original one is tied to the label. The one you create isn't associated with any widgets so it will never be visible.

The second problem is that you're associating the variable with the label incorrectly. You're doing this:

reading_display = Label(..., text = virtual_reading.get())

... when you should be doing it like this to get the auto-update feature:

reading_display = Label(..., textvariable = virtual_reading)

That being said, you don't need to use a StringVar at all. You can use it, but it's just an extra object you have to manage. You can directly set the displayed string with the configure method anytime you want

text = "{} {:.3f} {}".format(sign, reading, units)
reading_display.configure(text=text)

Note: you do not need to call update or update_idletasks

https://en.xdnf.cn/q/118800.html

Related Q&A

Can someone help me installing pyHook?

I have python 3.5 and I cant install pyHook. I tried every method possible. pip, open the cmd directly from the folder, downloaded almost all the pyHook versions. Still cant install it.I get this error…

What is the bit-wise NOT operator in Python? [duplicate]

This question already has answers here:The tilde operator in Python(10 answers)Closed last year.Is there a function that takes a number with binary numeral a, and does the NOT? (For example, the funct…

PyQt QScrollArea no scrollarea

I haveclass View(QtWidgets.QLabel):def __init__(self):super(View,self).__init__()self.cropLabel = QtWidgets.QLabel(self)self.label = QtWidgets.QLabel(self)self.ogpixmap = QtGui.QPixmap()fileName = rC:/…

svg tag scraping from funnels

I am trying to scrape data from here but getting error. I have taken code from here Scraping using Selenium and pythonThis code was working perfectly fine but now I am getting errorwait.until(EC.visibi…

Python search for multiple values and show with boundaries

I am trying to allow the user to do this:Lets say initially the text says:"hello world hello earth"when the user searches for "hello" it should display:|hello| world |hello| earthhe…

Python: create human-friendly string from a list of datetimes

Im actually looking for the opposite of this question: Converting string into datetimeI have a list of datetime objects and I want to create a human-friendly string from them, e.g., "Jan 27 and 3…

Python replace non digit character in a dataframe [duplicate]

This question already has answers here:Removing non numeric characters from a string in Python(9 answers)Closed 5 years ago.I have the following dataframe column>>> df2[Age]1 25 2 35 3 …

PyGame.error in ubuntu

I have problem with pygame and python 3 in ubuntu 12.10. When i tried load an image i got this error: pygame.error: File is not a Windows BMP fileBut in python 2.7 all works fine. I use code from http:…

Firebase Admin SDK with Flask throws error No module named firebase_admin

--- Question closedIt was my mistake, my uWSGI startup script switches to a different virtualenv.--- Original questionIm trying to publish push notifications from my Flask app server to Android APP. Se…

Recursive generator for change money - python

First, thanks for any help. I have this recursive code for counting ways of change from a list of coins and a given amount. I need to write a recursive generator code that presents the ways in every it…