python - 在 TKinter 中禁用/启用按钮
问题描述
我正在尝试制作一个像开关一样的按钮,所以如果我单击禁用按钮,它将禁用“按钮”(有效)。如果我再次按下它,它将再次启用它。
我尝试了 if, else 之类的东西,但没有让它工作。这是一个例子:
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()
解决方案
TkinterButton
具有三种状态:active, normal, disabled
.
您将state
选项设置disabled
为使按钮变灰并使其无响应。它active
在鼠标悬停时具有值,默认值为normal
.
使用它,您可以检查按钮的状态并采取所需的操作。这是工作代码。
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()
推荐阅读
- java-8 - Log4j-Slf4j 通过省略 -configFile 但采用 -configuration 表现得很奇怪
- webpack - 如何使用 CRACO Webpack 配置使用 Tailwind CSS 构建 React Styleguidist?
- delphi - Outlook:将附件保存到 FTP 服务器
- python - 如何在 Windows 10 中的 python 中运行 LAMMPS?
- typescript - 如何在 TypeScript 中获取重载方法的第一个参数类型
- angular - 注入解析器时出现 ResolverFactory 注入问题
- android - React-native 应用程序卡在 app:installDebug
- java - 大小为 x 的子数组中最小值的最大值
- azure - 部署 Azure 应用服务时出错:ERROR_COULD_NOT_CONNECT_TO_REMOTESVC
- reactjs - 如何在反应测试库中测试单选按钮(用户可以选择其他单选按钮)