Disabling a button but visually keeping it as if it wasn't disabled

﹥>﹥吖頭↗ 提交于 2020-06-27 12:27:20

问题


for my board game, I need to press a certain button and after that, disable it (to prevent the user or the computer to place a "peace" in the same place). The problem I have with this is basically design-wise: as you would know, when a button is disabled in tkinter, it turns grayed-out, kinda "visually blocking" the piece I placed... Here is an image of what I'm talking about:

enter image description here

My question is, how would I disable a button, but keep it as if it wasn't disabled? I searched and the only answer I came about was basically getting rid of the button and replacing it with an image... If that's my best bet, how would I do this? the grid is created with a for loop that fills a list with buttons, and then displays them into a frame using the grid() method. This would look like:

enter image description here

Is there another way to achieve this with tkinter methods? I would rather not change the buttons to an image with a bound event, that seems too complicated given that I'd have to mess with my loop. Thanks!!

Thanks!


回答1:


Turns out in order to disable the button but keeping its appearance, you have to disable its callback to make it "unresponsive" (as stated by @Bryan Oakley and @martineau, thanks!) and also change its 'relief' as to make it stay "fixed" (it kind of shifts into the bottom right corner, but that's good enough).

Imagine you have this generic button:

button = tkinter.Button(frame, height=0, bg='blue',\
                    activebackground='blue',width = 0, text = " ", image = self.blank, \
                    command=lambda row=row_index, \
                        column=column_index: \
                        self.button_clicked(row,column))

Now when you want to disable it but keeping its original appearance, you change the following attributes of the button:

button['command'] = 0 #this disables the callback
button['relief'] = 'sunken' #makes the button fixed

As easy as that! thanks!




回答2:


You can control the foreground and background colors with a variety of options, such as foreground, background, disabledforeground, and highlightbackground. Have you tried setting any of those to get the visual behavior you want?

You also have the option of disabling the callback, so the button will press but it won't do anything. To disable it, simply configure the command option to be None:

the_button.configure(command=None)


来源:https://stackoverflow.com/questions/20172615/disabling-a-button-but-visually-keeping-it-as-if-it-wasnt-disabled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!