【问题标题】:How to update a global counter如何更新全局计数器
【发布时间】:2020-09-05 04:56:14
【问题描述】:

我正在尝试在 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 放在很多地方,但都没有奏效。所以我想问题是 Count 的值会在每个循环(mainloop())中重置为 0。对tkinter不太熟悉。我最终想用这个计数器做的是每次按下按钮时更新窗口中显示的“对话”(标签和按钮)。按下不同的按钮应该会产生不同的对话(比如那种文字游戏)。谁能帮我解决这个问题?

【问题讨论】:

标签: python python-3.x tkinter mainloop


【解决方案1】:

使用按钮时需要传递函数,而不是调用它。这意味着您之后输入的函数名称不带括号,因此无法使用任何参数调用它。此外,您使用 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')

【讨论】:

    【解决方案2】:

    在您的情况下,您需要在要更新它的函数中将 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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-14
      • 2016-02-16
      • 2022-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      相关资源
      最近更新 更多