0

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()
7
  • 1
    Instead of "active" use "normal" Commented May 2, 2021 at 9:20
  • 2
    Also instead of command=lambda: switch1 use command=switch1. Also also you know that when the button is disabled it can't be clicked so the user can't re enable it. What exactly are you trying to do? Commented May 2, 2021 at 9:22
  • I wanted to disbale and re-enable a function by clicking on the button. I guess I try it with a variable for True and False Commented May 2, 2021 at 15:15
  • You can add another button that toggles button1's state. What exactly are you trying to do? Why do you want to toggle the button? Commented May 2, 2021 at 15:17
  • I want to disbale and re-enable a function by clicking on the Button. Commented May 2, 2021 at 15:19

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

If anyone is crazy and wants a oneliner ~ command=lambda: button1.config(state="disabled") if button1.cget("state") == "normal" else button1.config(state="normal").
@CoolCloud Nice 1 liner. I never knew that you can put if statements inside lambdas :D
Yes, but it single handedly violated PEP8's rule of 80 characters in one line :P
@CoolCloud Also the zen of python PEP 20. Lets see how many PEPs you can violate with 1 line of code :D
thanks that works. The one liner get's me confused :D
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.