我有以下问题,我有一个7 x 7网格填充butoons,以下问题是: 我想稍后在按钮上替换文本,但是在行和列的帮助下,这怎么可能?
import tkinter as tk
def click(row, col):
print(row, col)
label.configure(text="you clicked row %s column %s" % (row, col))
test_text = "TEST"
root = tk.Tk()
for row in range(1,8):
for col in range(1,8):
button = tk.Button(root, text=test_text,
command=lambda row=row, col=col: click(row, col))
button.grid(row=row, column=col, sticky="nsew")
label = tk.Label(root, text="")
label.grid(row=8, column=1, columnspan=8, sticky="new")
root.grid_rowconfigure(10, weight=1)
root.grid_columnconfigure(10, weight=1)
root.mainloop()
答案 0 :(得分:0)
您需要保留对按钮的引用以更改其文本。这是一个例子。
import tkinter as tk
def click(row, col):
print(row, col)
label.configure(text="you clicked row %s column %s" % (row, col))
buttons[row-1][col-1].config(text='Foo')
test_text = "TEST"
root = tk.Tk()
buttons = []
for row in range(1,8):
button_row = []
for col in range(1,8):
button = tk.Button(root, text=test_text,
command=lambda row=row, col=col: click(row, col))
button.grid(row=row, column=col, sticky="nsew")
button_row.append(button)
buttons.append(button_row)
label = tk.Label(root, text="")
label.grid(row=8, column=1, columnspan=8, sticky="new")
root.grid_rowconfigure(10, weight=1)
root.grid_columnconfigure(10, weight=1)
root.mainloop()
我必须在处理程序中使用row-1
和col-1
来更正索引。