I am trying to make a button that increments a variable with Tkinter, but when I 'call' (I know it isn't really calling) a function with command
, i can not use return variable
, as there is nowhere to return the variable to. Are there alternative ways to do this? Here is my code:
import tkinter as tk
variable = 0
root = tk.Tk()
def variable_incrementer():
global variable
variable += 1
# Not return here
click_btn = tk.Button(root, text="Click me", command=variable_incrementer)
click_btn.pack()
root.mainloop()
You don't need to return from the call-back, Instead, you can update the label directly and you used .push()
but actually Tkinter widgets uses .grid()
, .pack()
or .place()
to display them?
here is the updated code:
import tkinter as tk
variable = 0
root = tk.Tk()
label = tk.Label(root, text=f"Count: {variable}")
label.pack()
def variable_incrementer():
global variable
variable += 1
label.config(text=f"Count: {variable}")
click_btn = tk.Button(root, text="Click me", command=variable_incrementer)
click_btn.pack()
root.mainloop()