如何更新全局计数器

How to update a global counter

我正在尝试在 tkinter 中实现一个计数器。每当我单击任何一个按钮时,我都希望它 +1。但是,计数器值始终保持不变。这是我的示例代码:

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()

实际上我在很多地方都尝试过使用 Count+=1,但是 none 成功了。所以我猜问题是在每个循环(mainloop())中 Count 的值将被重置为 0。对 tkinter 不太熟悉。我最终想用这个计数器做的是每次按下按钮时更新 window 中显示的 "dialogue"(标签和按钮)。按下不同的按钮应该会产生不同的对话(就像那种文字游戏)。谁能帮我解决这个问题?

在您的情况下,您需要在要更新它的函数中将 Count 声明为全局:

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   # This is why global is needed

这意味着您的按钮可以是这样的:

tk.Button(window, textvariable = str1, command=callback1).pack(side='right',expand='yes')
tk.Button(window, textvariable = str2, command=callback2).pack(side='right',expand='yes')
tk.Button(, textvariable = str3, command=callback3).pack(side='right',expand='yes')

使用按钮时需要传递函数,而不是调用函数。这意味着您之后输入的函数名称不带括号,因此不能使用任何参数调用它。此外,您使用 lambda 定义单行函数,而不是使用您已经定义的函数,如 callback1 的情况。 Lambda 函数没有名称,因此 callback23 会导致错误。此代码将起作用:

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')