用按钮单击更改按钮文本无效

2024-03-29 09:29:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在给扫雷舰编程。我已经完成了所有的逻辑,现在我只是做图形用户界面。我用的是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语句,因此我知道它将到达那里,但它不会更改按钮文本。非常感谢您的帮助!你知道吗


Tags: thetextinboxeventnewifis
1条回答
网友
1楼 · 发布于 2024-03-29 09:29:59

我认为问题在于你试图将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 = []

相关问题 更多 >