我遇到了一个问题,我使用循环创建了一个按钮表,并将按钮的名称保存在一个列表中,现在我想在单击一个按钮时更改按钮的文本。 我不知道如何。
这是我创建表格的循环
def grid(n):
i = n*n
for widget in LeftFrame.winfo_children():
widget.destroy()
for i in range(n):
for row in range(n):
for col in range(n):
button = Button(LeftFrame, text=' ', width=12, height=6, command=lambda: checker(button, i))
button.grid(row=row, column=col)
button_identities.append(button)
这是点击按钮的功能
def checker(buttons, i):
print(i)
global click, button_identities
print(button_identities)
bname = (button_identities[i])
print(bname)
if buttons["text"] == ' ' and click == True:
buttons["text"] = 'X'
click = False
# scorekeeper()
elif buttons['text'] == ' ' and click == False:
buttons['text'] = 'O'
click = True
# scorekeeper()
有一种方法可以检查最后一个函数中按钮名称的文本
答案 0 :(得分:1)
试试这个:
from functools import partial
def grid(n):
for widget in LeftFrame.winfo_children():
widget.destroy()
for i in range(n):
for row in range(n):
for col in range(n):
button = Button(LeftFrame, text=' ', width=12, height=6)
# Assign the button a command
command = partial(checker, button)
button.config(command=command)
button.grid(row=row, column=col)
button_identities.append(button)
def checker(button):
# The argument is a button
global click
# If the cell is empty
if button.cget("text") == " ":
# If Xs are you play
if click:
# Change the text of the button
button.config(text="X")
click = False
# If Os are to play
else:
# Change the text of the button
button.config(text="O")
click = True
我通常使用 <widget>.cget("<parameter>")
从小部件中获取参数,并使用 <widget>.config(parameter=<new value>)
为其分配一个新值。您也可以使用 functools.partial
为按钮命令传递参数。
答案 1 :(得分:0)
所以这是我对这个问题的看法:
from tkinter import Tk, Button
root = Tk()
class EditableButton(Button):
def __init__(self, parent, row, col):
Button.__init__(self, parent)
self.parent = parent
self.row = row
self.col = col
self.tracker = 0
self.name_list = ['apple', 'pear']
print(len(self.name_list))
self.button = Button(self.parent, text=self.name_list[self.tracker], command=self.change_text)
self.button.grid(row=self.row, column=self.col)
def change_text(self):
if self.tracker < len(self.name_list) - 1:
self.tracker += 1
else:
self.tracker = 0
self.button.config(text=self.name_list[self.tracker])
n = 3
for row in range(n):
for col in range(n):
button = EditableButton(root, row, col)
root.mainloop()
基本上发生的事情是你创建了一个类似于按钮模板的类,循环创建的每个类对象都是独立的,每个类对象在内存中都有自己的位置,所以每当你按下按钮时,它只会调用函数在它自己的类中