简体   繁体   中英

How to determine which Button has been clicked?

I'm in the early stages of creating a memory game. What I would like is to be able to tell which button has been pressed, but I have no idea how to do this. For example, upon clicking a button, the text changes to something else.

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

Here how to arrange the Button s in a grid as well as define a function to change the text on them when they are clicked. Note that the Button had to be created before a function to change it could be defined because the function need to refers to it.

Also note I have modified your code to follow the PEP 8 - Style Guide for Python Code guidelines to make it more readable. I suggest you read and start following it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM