【问题标题】:Locking configuration of a button in tkinter在 tkinter 中锁定按钮的配置
【发布时间】:2018-01-15 18:56:28
【问题描述】:

所以我想知道是否有我可以使用的功能/命令来停止重新配置按钮。在我的程序中,我有一个按钮列表,每次单击按钮(事件)时,按钮内的值都会增加一。但是,有几个按钮我不希望出现这种循环功能 - 对我如何实现这一点有任何帮助吗?我将在下面展示我的代码生成按钮的位置以及事件函数的位置。

def LeftClick(event):
    if c==True:
        next_value = " 123456789 "
        try:
            current_value = next_value[next_value.index(str(int(event.widget['text']))) + 1]
        except ValueError:
            current_value = "1"

        event.widget.config(text=current_value)

#Create a 9x9 (rows x columns) grid of buttons inside the frame
for row_index in range(9):
    for col_index in range(9):
        if (row_index in {0, 1, 2, 6, 7, 8} and col_index in {3, 4, 5}) or \
                (row_index in {3, 4, 5} and col_index in {0, 1, 2, 6, 7, 8}): #Colours a group of 3x3 buttons together to differentiate the board better.
            colour = 'gray85'
        else:
            colour = 'snow'
        c=True
        btn = Button(frame, width = 12, height = 6, bg=colour) #create a button inside frame 
        btn.grid(row=row_index, column=col_index, sticky=N+S+E+W)
        btn.bind("<Button-1>", LeftClick)
        buttons.append(btn)
        if row_index==4 and col_index==1:
            btn.config(text=2)
            c = False                   

我曾尝试使用 c 作为变量来确定哪些按钮可以更改,哪些按钮不能更改,但是没有成功。

【问题讨论】:

  • 您是添加绑定以添加此行为的人。您是否尝试过简单地为不应具有此行为的小部件添加绑定?
  • 否,因为那样它将解除所有绑定。我仍然想要大多数按钮的功能,而不是后者,
  • 我没有说全部解除绑定,只是解除你不想要的那些。您正在询问如何删除您自己添加的功能。该问题的正确解决方案是“不要添加它”。
  • 只需使用基本的if 语句。如果是普通按钮,请添加绑定。如果没有,不要。
  • 只需使用if c: btn.bind("&lt;Button-1&gt;", LeftClick)

标签: python button tkinter


【解决方案1】:

解决方案太简单了,写起来甚至很愚蠢

    c = True

    btn = Button(frame, width = 12, height = 6, bg=colour) 
    btn.grid(row=row_index, column=col_index, sticky=N+S+E+W)

    if row_index==4 and col_index==1:
        btn.config(text=2)
        c = False                   

    if c:
        btn.bind("<Button-1>", LeftClick)

    buttons.append(btn)

或者甚至没有c

    btn = Button(frame, width = 12, height = 6, bg=colour) 
    btn.grid(row=row_index, column=col_index, sticky=N+S+E+W)

    if row_index==4 and col_index==1:
        btn.config(text=2)
    else:
        btn.bind("<Button-1>", LeftClick)

    buttons.append(btn)

顺便说一句:按钮有command=,您可以使用它来代替bind('&lt;Button-1&gt;')

顺便说一句:c 是全局变量,它改变了for 循环内的值,因此它对LeftClick 内的所有按钮具有相同的值。

【讨论】:

    猜你喜欢
    • 2014-10-09
    • 1970-01-01
    • 2017-07-13
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 2021-01-05
    相关资源
    最近更新 更多