首页 > 解决方案 > Python:禁用和重新启用按钮

问题描述

我想创建一个我可以点击disablere-enable按钮。使用以下代码,我得到一个按钮,我可以disable,但是re-enable当我单击它时它不会。如果查看此威胁,但没有帮助:禁用/启用 TKinter 中的按钮

import tkinter
from tkinter import *

# toplevel widget of Tk which represents mostly the main window of an application
root = tkinter.Tk()
root.geometry('1800x600')
root.title('Roll Dice')
frame = Frame(root)

# label to display dice
label = tkinter.Label(root, text='', font=('Helvetica', 120))

# function activated by button
def switch1():
    if button1["state"] == "active":
        button1["state"] = "disabled"
    else:
        button1["state"] = "active"

button1 = tkinter.Button(root, text='Würfel 1', foreground='green', command=lambda: switch1, state = "active")

button1.pack(side = LEFT)

root.mainloop()

标签: python-3.xtkinterbutton

解决方案


看这个:

import tkinter as tk

def toggle_state():
    if button1.cget("state") == "normal":
        button1.config(state="disabled")
    else:
        button1.config(state="normal")

root = tk.Tk()

button1 = tk.Button(root, text="This button toggles state")
button1.pack()

button2 = tk.Button(root, text="Click me", command=toggle_state)
button2.pack()

root.mainloop()

这使用一个按钮来切换另一个按钮的状态。


推荐阅读