绑定到键盘的 Tkinter 按钮不计算 Class 参数

Tkinter Button Binded to Keyboard Won't Count Class Parameter

我正在尝试创建函数 'count',它接受一个变量形式的整数,并在每次按下 return 键时将其加 1,保存到变量中每次。

该参数需要保持通用,因为将来这将 运行 根据按下哪个按钮对多个变量执行相同的 'count' 函数。

我尝试通过将 global messi 放在顶部来使 messi 成为全局变量,但出现了同样的问题。

import tkinter as tk

class PlayerStats:
    def __init__(self, name, touches):
        team = "Barcelona"
        self.name = name
        self.touches = touches
        
    def count(number):
        number = number + 1
        print(number)

messi = PlayerStats("Messi",0)

root = tk.Tk()
root.bind('<Return>', lambda event :PlayerStats.count(messi.touches))
root.mainloop()

当我 运行 这个片段时,它从 0 到 1 迭代它一次,然后重置总是打印出 1。

任何关于为什么会发生这种情况以及如何解决的想法将不胜感激!!

您没有保存操作结果。

您正在实例化您的 PlayerStats class,touches 的值为 0。 该值在您的代码中永远不会发生变化。

当 tkinter 调用您的 count 方法时,它会递增 number 但该变量永远不会离开方法的范围,因此会被垃圾收集。

要修复它,您应该将 class 更改为

import tkinter as tk

class PlayerStats:
    def __init__(self, name, touches):
        team = "Barcelona"
        self.name = name
        self.touches = touches
        
    def count(self):  # the first argument of a method is always a reference to the instance
        self.touches += 1
        print(self.touches)

messi = PlayerStats("Messi", 0)

root = tk.Tk()
root.bind('<Return>', lambda event: messi.count())  # You need to call the method on the instance you created.
root.mainloop()

感谢狗狗的帮助。我上面的功能代码现在看起来像这样:

import tkinter as tk

class PlayerStats:
    def __init__(self, name, touches):
        team = "Barcelona"
        self.name = name
        self.touches = touches
        
    def count(self, number):
        self.touches += 1
        print(number)

messi = PlayerStats("Messi",0)

root = tk.Tk()
root.bind('<Return>', lambda event :messi.count(messi.touches))
root.mainloop()

虽然这没有解决的一件事是能够为不同的变量重用该函数。我现在正试图想出一种优雅的方式来做这样的事情: 将 tkinter 导入为 tk

class PlayerStats:
    def __init__(self, name, touches, shots):
        team = "Barcelona"
        self.name = name
        self.touches = touches
        self.shots = shots

    def count(self, number):
        self.number += 1
        print(number)

messi = PlayerStats("Messi",0)

root = tk.Tk()
root.bind('<Return>', lambda event :messi.count(messi.touches))
root.bind('<s>', lambda event :messi.count(messi.shots))
root.mainloop()

其中数字代表 messi.shots 或 messi.touches,具体取决于按下的键。我想在不为每个键重新创建一堆几乎相同的函数的情况下执行此操作。