I am trying to implement a counter in tkinter. I expect it to +1 whenever I click whichever button. However, the counter value always remains the same. Here is my sample code:
import tkinter as tk
import time
Count=0
def callback1(Count):
print(Count)
if Count == 1:
texts.set('a')
str1.set('1')
str2.set('2')
str3.set('3')
if Count == 2:
texts.set('b')
str1.set('1')
str2.set('2')
str3.set('3')
Count+=1
#(I have omitted callback2 and callback3 because they are basically the same as callback1)
window = tk.Tk()
texts=tk.StringVar('')
window.title('Test')
window.geometry('400x200')
l=tk.Label(window,
textvariable=texts,
font=('Arial',12),
)
l.pack()
str1=tk.StringVar('')
str2=tk.StringVar('')
str3=tk.StringVar('')
tk.Button(window, textvariable = str1, command = lambda: callback1(Count)).pack(side='right',expand='yes')
tk.Button(window, textvariable = str2, command = lambda: callback2(Count)).pack(side='right',expand='yes')
tk.Button(window, textvariable = str3, command = lambda: callback3(Count)).pack(side='right',expand='yes')
tk.mainloop()
I actually tried to put Count+=1 in many places, but none worked. So I guess the problem is that the value of Count would be reset to 0 in every loop (mainloop()). Not so familiar with tkinter. What I want to do with this counter ultimately, is to update the "dialogue" (label & buttons) shown in the window every time I press the buttons. And pressing different buttons should yield different dialogue (like that kind of text games). Could anyone help me with this?
You need to pass the function when using the button, not call it. That means that you enter the name of the function without parenthesis afterward and thus can't call it with any arguments. Also, you use lambda to define a one-line function, not to use the one you have already defined, as in case of callback1
. Lambda functions don't have names, so callback2
and 3
will cause an error. This code will work:
Count = 0
def callback1():
global Count
print(Count)
if Count == 1:
texts.set('a')
str1.set('1')
str2.set('2')
str3.set('3')
if Count == 2:
texts.set('b')
str1.set('1')
str2.set('2')
str3.set('3')
Count += 1
tk.Button(window, textvariable=str1, command=callback1).pack(side='right', expand='yes')