Mazze
Mazze

Reputation: 443

Python: disable and re-enable button

I want to create a button that I can disable and re-enable as soon as I click it. With the following code, I get a button that I can disable, but it won't re-enable when I click it. If looked at this threat, but it didn't help: Disable / Enable Button in 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()

Upvotes: 0

Views: 4101

Answers (1)

TheLizzard
TheLizzard

Reputation: 7680

Look at this:

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()

This uses a button to toggle the state of the other button.

Upvotes: 2

Related Questions