I am trying to update information in tkinter labels and buttons without redrawing entire screens. I’m using Python 3, a Raspberry Pi, and Idle. I have a trivial example of what I am trying to do. I see comments here that suggest I need to learn to manipulate stringvariable or IntVar, etc. but my book is totally unhelpful in that regard. In this example, I would like the number between the buttons to track the value of the number as it changes with button pushes.
##MoreOrLess.01.py from tkinter import * global number number = 5 root = Tk() root.title("Test Buttons") def Less(): global number number -= 1 print ("The number is now ", number) def More(): global number number += 1 print("The number is now ", number) def MakeLabel(number): textvariable = number label1 = Label(root, text = "Pick a button please.").pack(pady=10) btnL = Button(root, text = "More", command = More).pack(side = LEFT) btnR = Button(root, text = "Less", command = Less).pack(side = RIGHT) label2 = Label(root, text = number).pack(pady = 20) MakeLabel(number)
Answer
Not only do you base yourself in a book, check the official documentation of tkinter. in your case you must create a variable of type IntVar
with its set()
and get()
method, and when you want to link that variable through textvariable
.
from tkinter import * root = Tk() root.title("Test Buttons") number = IntVar() number.set(5) def Less(): number.set(number.get() - 1) print ("The number is now ", number.get()) def More(): number.set(number.get() + 1) print("The number is now ", number.get()) def MakeLabel(number): textvariable = number label1 = Label(root, text = "Pick a button please.").pack(pady=10) btnL = Button(root, text = "More", command = More).pack(side = LEFT) btnR = Button(root, text = "Less", command = Less).pack(side = RIGHT) label2 = Label(root, textvariable = number).pack(pady = 20) MakeLabel(number) root.mainloop()