-1

I am trying to update my label in Tkinter with the value of "x" for every time that "x" changes value. Almost like a live counter. This is a simplified loop because I am working on Pycharm. Eventually I would like to modify this code so that the label is updated with the values from a temperature sensor connected to my Raspberry Pi. Please can some assistance be provided on this topic, Thanks :)

from Tkinter import *
import tkFont
import time

# Window
root = Tk()
root.geometry("700x600+550+100")

# Font
font = tkFont.Font(family = 'Halvetica', size = 36, weight = 'bold')

x = 0

def do():
    list = [1, 2, 3, 4]
    for x in list:
        temp = Label(root, text=x, fg="black", heigh=2, width=15, font=font)
        temp.pack()
        time.sleep(2)
        #temp["text"] = x


do()

root.mainloop()

I expected the program to print 1, then replace 1 with 2 and so forth. I do not want 1,2,3,4 to be presented all together.

When I execute the code it presents me with the numbers 1 to 4 but it did not update it live and they are below each other which is not that I want

  • 1
    use `tkinter.after(miliseconds, function_name)` to execute function every 2000ms (2s) – furas Dec 10 '17 at 21:30
  • 1
    BTW: you don't have to create `Label` again to change text - `temp["text"] = "new text"` but you will have to remeber label in global variable. – furas Dec 10 '17 at 21:31
  • 1
    example how to use `after` to [display current time in label](https://github.com/furas/python-examples/blob/master/tkinter/timer-using-after/clock-function.py) – furas Dec 10 '17 at 21:32
  • 1
    BTW: it doesn't work because it blocks `mainloop()` which gets events from system, sends event to widgets, redraws widgets (and all in loop). – furas Dec 10 '17 at 21:34
  • 1
    There are many questions on this site about running a function periodically, reading a sensor, and updating labels or other widgets. Have you done any research before asking? – Bryan Oakley Dec 10 '17 at 22:00

1 Answers1

0

In your code the 1, 2, 3, 4 are presented altogether because you're creating a new label and calling it temp for the scope of do each time the for loop is iterating. Instead you should make a label and update it's text like:

temp = tkinter.Label(...)

for(...):
    temp['text'] = "Updated String Here"

Also if you use time.sleep it makes your entire GUI to be sleeped as well, try using after method that is available for tkinter widgets like:

root.after(1000, callback_func)

will call callback_func every 1000 milisecond.

Nae
  • 14,209
  • 7
  • 52
  • 79