本文介绍了在 TKinter 中禁用/启用按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个像开关一样的按钮,所以如果我点击禁用按钮它将禁用按钮"(有效).如果我再次按下它,它会再次启用它.

I'm trying to make a button like a switch, so if I click the disable buttonit will disable the "Button" (that works). And if I press it again, it will enable it again.

我尝试了 if, else 之类的东西,但没有让它起作用.举个例子:

I tried things like if, else but didn't get it to work.Here's an example:

from tkinter import *
fenster = Tk()
fenster.title("Window")

def switch():
    b1["state"] = DISABLED

#--Buttons
b1=Button(fenster, text="Button")
b1.config(height = 5, width = 7)
b1.grid(row=0, column=0)

b2 = Button(text="disable", command=switch)
b2.grid(row=0,column=1)

fenster.mainloop()

推荐答案

A Tkinter Button 具有三种状态:active, normal, disabled.

A Tkinter Button has three states : active, normal, disabled.

您将 state 选项设置为 disabled 以使按钮变灰并使其无响应.当鼠标悬停在它上面时,它的值为 active,默认值为 normal.

You set the state option to disabled to gray out the button and make it unresponsive. It has the value active when the mouse is over it and the default is normal.

使用它,您可以检查按钮的状态并采取所需的操作.这是工作代码.

Using this you can check for the state of the button and take the required action. Here is the working code.

from tkinter import *

fenster = Tk()
fenster.title("Window")

def switch():
    if b1["state"] == "normal":
        b1["state"] = "disabled"
        b2["text"] = "enable"
    else:
        b1["state"] = "normal"
        b2["text"] = "disable"

#--Buttons
b1 = Button(fenster, text="Button", height=5, width=7)
b1.grid(row=0, column=0)

b2 = Button(text="disable", command=switch)
b2.grid(row=0, column=1)

fenster.mainloop()

这篇关于在 TKinter 中禁用/启用按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 04:21