Python tkinter button state

How to change Tkinter Button state from disabled to normal?

I need to change the state of a Button from DISABLED to NORMAL when some event occurs. The button is currently created in the DISABLED state using the following code:

self.x = Button(self.dialog, text="Download", state=DISABLED, command=self.download).pack(side=LEFT) 

3 Answers 3

You simply have to set the state of the your button self.x to normal :

This code would go in the callback for the event that will cause the Button to be enabled.

Also, the right code should be:

self.x = Button(self.dialog, text="Download", state=DISABLED, command=self.download) self.x.pack(side=LEFT) 

The method pack in Button(. ).pack() returns None , and you are assigning it to self.x . You actually want to assign the return value of Button(. ) to self.x , and then, in the following line, use self.x.pack() .

It should be added that this code would go in the callback for the event that will cause the button to be enabled.

I tried got the error: self.x[‘state’] = ‘enabled’ : ‘NoneType’ object does not support item assignment

I think a quick way to change the options of a widget is using the configure method.

In your case, it would look like this:

self.x.configure(state=NORMAL) 

This is what worked for me. I am not sure why the syntax is different, But it was extremely frustrating trying every combination of activate, inactive, deactivated, disabled, etc. In lower case upper case in quotes out of quotes in brackets out of brackets etc. Well, here’s the winning combination for me, for some reason.. different than everyone else?

import tkinter class App(object): def __init__(self): self.tree = None self._setup_widgets() def _setup_widgets(self): butts = tkinter.Button(text = "add line", state="disabled") butts.grid() def main(): root = tkinter.Tk() app = App() root.mainloop() if __name__ == "__main__": main() 

Источник

Tkinter Button

Summary: in this tutorial, you’ll learn about the Tkinter Button widget and how to use it to create various kinds of buttons.

Introduction to Tkinter button widget

Button widgets represent a clickable item in the applications. Typically, you use a text or an image to display the action that will be performed when clicked.

Buttons can display text in a single font. However, the text can span multiple lines. On top of that, you can make one of the characters underline to mark a keyboard shortcut.

To invoke a function or a method of a class automatically when the button is clicked, you assign its command option to the function or method. This is called the command binding in Tkinter.

To create a button, you use the ttk.Button constructor as follows:

button = ttk.Button(container, **option)Code language: Python (python)

A button has many options. However, the typical ones are like this:

button = ttk.Button(container, text, command)Code language: Python (python)
  • The container is the parent component on which you place the button.
  • The text is the label of the button.
  • The command specifies a callback function that will be called automatically when the button clicked.

Command callback

The command option associates the button’s action with a function or a method of a class. When you click or press the button, it’ll automatically invoke a callback function.

To assign a callback to the command option, you can use a lambda expression:

def callback(): # do something ttk.Button( root, text="Demo Button", command=callback )Code language: Python (python)

If the function contains one expression, you use a lamba expression:

ttk.Button( root, text="Demo Button", command=lambda_expression )Code language: Python (python)

Button states

The default state of a button is normal . In the normal state, the button will respond to the mouse events and keyboard presses by invoking the callback function assigned to its command option.

The button can also have the disabled state. In the disabled state, a button is greyed out and doesn’t respond to the mouse events and keyboard presses.

To control the state of a button, you use the state() method:

# set the disabled flag button.state(['disabled']) # remove the disabled flag button.state(['!disabled'])Code language: Python (python)

Tkinter button examples

Let’s take some examples of using button widgets.

1) Simple Tkinter button example

The following program shows how to display an Exit button. When you click it, the program is terminated.

import tkinter as tk from tkinter import ttk # root window root = tk.Tk() root.geometry('300x200') root.resizable(False, False) root.title('Button Demo') # exit button exit_button = ttk.Button( root, text='Exit', command=lambda: root.quit() ) exit_button.pack( ipadx=5, ipady=5, expand=True ) root.mainloop()Code language: Python (python)

The following creates the Exit button:

exit_button = ttk.Button( root, text='Exit', command=lambda: root.quit() )Code language: Python (python)

The command of the button is assigned to a lambda expression that closes the root window.

2) Tkinter image button example

The following program shows how to display an image button. To practice this example, you need to download the following image first:

Just right-click and save it into a folder that is accessible from the following program e.g., assets folder:

import tkinter as tk from tkinter import ttk from tkinter.messagebox import showinfo # root window root = tk.Tk() root.geometry('300x200') root.resizable(False, False) root.title('Image Button Demo') # download button def download_clicked(): showinfo( title='Information', message='Download button clicked!' ) download_icon = tk.PhotoImage(file='./assets/download.png') download_button = ttk.Button( root, image=download_icon, command=download_clicked ) download_button.pack( ipadx=5, ipady=5, expand=True ) root.mainloop()Code language: Python (python)

  • First, create a new instance of the tk.PhotoImage class that references the image file ‘./assets/download.png’ .
  • Second, create the ttk.Button whose image option is assigned to the image.
  • Third, assign a function to the command option. When you click the button, it’ll call the download_clicked function that displays a message box.

3) Displaying an image button

To display both text and image on a button, you need to use the compound option. If you don’t, the button will display the text only, not the image.

The following shows how to display both text and image on a button:

import tkinter as tk from tkinter import ttk from tkinter.messagebox import showinfo # root window root = tk.Tk() root.geometry('300x200') root.resizable(False, False) root.title('Image Button Demo') # download button handler def download_clicked(): showinfo( title='Information', message='Download button clicked!' ) download_icon = tk.PhotoImage(file='./assets/download.png') download_button = ttk.Button( root, image=download_icon, text='Download', compound=tk.LEFT, command=download_clicked ) download_button.pack( ipadx=5, ipady=5, expand=True ) root.mainloop() Code language: Python (python)

Summary

  • Use the ttk.Button() class to create a button.
  • Assign a lambda expression or a function to the command option to respond to the button click event.
  • Assign the tk.PhotoImage() to the image property to display an image on the button.
  • Use the compound option if you want to display both text and image on a button.

Источник

Change Tkinter Button State

Change Tkinter Button State

The left button is disabled (gray out) and the right button is normal.

Tkinter Button States - DISABLED and NORMAL

The states could be modified in the dictionary-like method or configuration-like method.

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

By clicking button2 , it calls the function switchButtonState to switch button1 state from DISABLED to NORMAL , or vice versa.

state is the option of Tkinter Button widget. All the options in the Button widget are the keys of Button as a dictionary.

def switchButtonState():  if (button1['state'] == tk.NORMAL):  button1['state'] = tk.DISABLED  else:  button1['state'] = tk.NORMAL 

The state is updated by changing the value of state in the Button dictionary.

The state could also be modified by using config method of Button object. Therefore, the switchButtonState() function could also be implemented as below,

def switchButtonState():  if (button1['state'] == tk.NORMAL):  button1.config(state=tk.DISABLED)  else:  button1.config(state=tk.NORMAL) 

Even the strings normal and disabled could be simply used rather than tk.NORMAL and 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.

Related Article — Tkinter Button

Источник

Читайте также:  Throw exception in java with example
Оцените статью