tkinter 按钮引用自身属性

tkinter button reffer self atribute

A 有一个包含 38 个按钮的网格 (num0-num38)。 我正在尝试将按钮属性(文本)传递给打印函数。

Code:
def collect_num(num):
    print(num)

num0 = tk.Button(buttons, text="0", padx=10, pady=5, fg="white", bg="green", command=collect_num(thisItem.text))

Python中有没有类似thisItem.text的东西? 所以基本上,我想在按下相应按钮时打印按钮名称(text="0" - text="38")。

如有任何帮助,我们将不胜感激。

您需要使用 partial(<function>, *args) 函数

传递按钮文本
from functools import partial

def collect_num(num):
    print(num)

# create the button first and add some specs like `text`
button = tk.Button(
  buttons, text="0", padx=10, pady=5, fg="white", bg="green"
)

# add command after creation with the above function and button's name
button.config(command=partial(collect_num, button["text"]))

在这个stack question的帮助下:

text = button["text"]

这是获取文本的方法。

text = button.cget('text')

或(在@TheLizzard 的帮助下)

text = button.config("text")[-1]

既然你问了一个例子,请看这里:

from tkinter import *

root = Tk()
MAX_BUTTON = 25 # Maximum number of buttons to be made

def collect_num(num):
    print(num) # Print the number

btns = [] # A list to add all the buttons, to make them reusable later
for i in range(MAX_BUTTON): # Looping 25 times or maximum number of buttons, times
    btns.append(Button(root,text=i,width=10))  # Creating a button and adding it to list
    btns[-1]['command'] = lambda x=btns[-1].cget('text'): collect_num(x) # Changing the command of the button
    btns[-1].pack() # Packing it on

root.mainloop()

此处cget()returns小部件的当前属性。

强烈建议这样做,而不是手动一个接一个地创建按钮。软件工程中有一个原则叫DRY,意思是Don't Repeat Yourself,意思就是如果你重复自己,可能会有办法不重复自己,减少写的代码。这种循环和创建小部件并使用 lambda 制作 command 的方法在需要制作多个带有图案的小部件时经常使用。