【问题标题】:How to determine which Button has been clicked? [duplicate]如何判断哪个Button被点击了? [复制]
【发布时间】:2022-08-19 10:47:28
【问题描述】:

我正处于创建记忆游戏的早期阶段。 我想要的是能够知道按下了哪个按钮,但我不知道该怎么做。例如,单击按钮后,文本会更改为其他内容。

from tkinter import *
import random

root = Tk()

root.title(\"Memory Game\")

buttons=[]#Stores the buttons

counter=0
x=0
y=0

for l in range(0,6):#Creates a grid of 36 working buttons and stores them in \"buttons\"
  x=0
  y+=1
  for i in range(0,6):
    buttons.append(Button(root,text=\"???\"))
    buttons[counter].grid(column = x, row = y)
    counter+=1
    x+=1

标签: python tkinter


【解决方案1】:

在这里如何在网格中排列Buttons 以及定义一个函数以在单击它们时更改其上的文本。请注意,Button 必须在定义更改它的函数之前创建,因为函数需要引用它。

另请注意,我已修改您的代码以遵循PEP 8 - Style Guide for Python Code 准则,使其更具可读性。我建议您阅读并开始关注它。

import tkinter as tk
import random

root = tk.Tk()

root.title("Memory Game")
buttons = []  # Stores the buttons.
width, height = 6, 6

# Creates a grid of width x height buttons and stores them in `buttons`.
for i in range(width * height):
    x, y = divmod(i, height)  # Calculate grid position.
    btn = tk.Button(root, text="???")

    # Define a function to change button's text.
    def change_text(b=btn):  # Give argument a default value so one does not
                             # need to be passed when it's called.
        b.config(text='*')  # Change button's text.

    btn.config(command=change_text)  # Configure button to call the function.
    btn.grid(column=x, row=y)  # Position the button in the matrix.
    buttons.append(btn)  # Save widget.

root.mainloop()

【讨论】:

    猜你喜欢
    • 2017-11-20
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 2010-10-18
    相关资源
    最近更新 更多