[英]How to determine which Button has been clicked?
我正處於創建 memory 游戲的早期階段。 我想要的是能夠知道按下了哪個按鈕,但我不知道該怎么做。 例如,單擊按鈕后,文本會更改為其他內容。
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
此處如何在網格中排列Button
以及定義 function 以在單擊它們時更改其上的文本。 請注意,必須在 function 之前創建Button
才能更改它,因為 function 需要引用它。
另請注意,我已修改您的代碼以遵循PEP 8 - Python 代碼指南的樣式指南,以使其更具可讀性。 我建議您閱讀並開始關注它。
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.