python - 使用按钮单击更改按钮文本不起作用
问题描述
我正在编程扫雷。我已经完成了所有的逻辑,现在我只是在做 GUI。我正在使用 Tkinter。板上有这么多空间,我想自动创建所有这些按钮,我是这样做的:
button_list = []
def create_buttons():
# Create the buttons
for x in range(code_squares):
# Code_squares is how many squares are on the board
new_button = Button(frame_list[x], text = "", relief = RAISED)
new_button.pack(fill=BOTH, expand=1)
new_button.bind("<Button-1>", lambda event: box_open(event, x))
button_list.append(new_button)
def box_open(event, x):
if box_list[x] == "M":
# Checks if the block is a mine
button_list[x].config(text="M", relief = SUNKEN)
# Stops if it was a mine
root.quit()
else:
# If not a mine, it changes the button text to the xth term in box_list, which is the amount of nearby mines.
print("in")
button_list[x].config(text=box_list[x], relief = SUNKEN)
print 语句只是一个测试。当我单击一个点时,它将执行打印语句,所以我知道它到达那里,但它不会更改按钮文本。非常感谢所有帮助!
解决方案
x
我相信问题在于您尝试嵌入的方式,请lambda
尝试一下,看看它是否可以解决您的问题:
from functools import partial
def create_buttons():
for n in range(code_squares):
# Code_squares is how many squares are on the board
new_button = Button(frame_list[n], text="", relief=RAISED)
new_button.pack(fill=BOTH, expand=1)
new_button.bind("<Button-1>", partial(box_open, x=n))
button_list.append(new_button)
def box_open(event, x):
if box_list[x] == "M":
# Checks if the block is a mine
button_list[x].config(text="M", relief=SUNKEN)
# Stops if it was a mine
root.quit()
else:
# If not a mine, it changes the button text to the xth
# term in box_list, which is the amount of nearby mines.
button_list[x].config(text=box_list[x], relief=SUNKEN)
button_list = []
推荐阅读
- php - 如何将多个多行文本展开为单行?
- jquery - Laravel:在 JQuery 中为每个添加一秒只会显示“未定义”
- html - 获取单击的输入字段行的所有值
- reactjs - Firebase 实时数据库有时未更新
- reactjs - Reactjs输入值没有改变
- azure - 使用分页列出 Azure Blob
- c - C 语言中是否有命令读取行,但不包括所有换行符?
- ruby-on-rails - 如何使用 login def 验证登录表单
- javascript - 如何在单个 JavaScript 文件中使用仅 ESM 的 npm 包和普通的 npm 包?
- android - 如何正确显示视图模型中的数据?