Come cambiare lo stato del pulsante Tkinter
Tkinter Button ha due stati,
NORMAL- Il pulsante può essere cliccato dall’utenteDISABLE- Il pulsante non è cliccabile
try:
import Tkinter as tk
except:
import tkinter as tk
app = tk.Tk()
app.geometry("300x100")
button1 = tk.Button(app, text="Button 1", state=tk.DISABLED)
button2 = tk.Button(app, text="EN/DISABLE Button 1")
button1.pack(side=tk.LEFT)
button2.pack(side=tk.RIGHT)
app.mainloop()
Il tasto sinistro è disabilitato (grigio fuori) e il tasto destro è normale.

Gli stati potrebbero essere modificati nel metodo simile al dizionario o nel metodo simile alla configurazione.
try:
import Tkinter as tk
except:
import tkinter as tk
def switchButtonState():
if button1["state"] == tk.NORMAL:
button1["state"] = tk.DISABLED
else:
button1["state"] = tk.NORMAL
app = tk.Tk()
app.geometry("300x100")
button1 = tk.Button(app, text="Python Button 1", state=tk.DISABLED)
button2 = tk.Button(app, text="EN/DISABLE Button 1", command=switchButtonState)
button1.pack(side=tk.LEFT)
button2.pack(side=tk.RIGHT)
app.mainloop()
Facendo clic su button2, chiama la funzione switchButtonState per passare dallo stato button1 da DISABLED a NORMAL, o viceversa.

state è l’opzione del widget Button di Tkinter. Tutte le opzioni del widget Button sono i tasti di Button come dizionario.
def switchButtonState():
if button1["state"] == tk.NORMAL:
button1["state"] = tk.DISABLED
else:
button1["state"] = tk.NORMAL
Lo state viene aggiornato cambiando il valore di state nel dizionario Button.
Lo state potrebbe anche essere modificato usando il metodo config dell’oggetto Button. Pertanto, la funzione switchButtonState() potrebbe anche essere implementata come segue,
def switchButtonState():
if button1["state"] == tk.NORMAL:
button1.config(state=tk.DISABLED)
else:
button1.config(state=tk.NORMAL)
Anche le stringhe normal e disable potrebbero essere semplicemente usate piuttosto che tk.NORMAL e tk.DISABLED.
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn Facebook