Tkinter Button Tutorial | Python GUI Tutorial

Tkinter Button Tutorial

In the window component, you can design the Button to perform a specific action when you click on it. This action is also called callback method, which means that we can use the Button as a bridge between the user and the program.

Button can have text on it, or it can have an image like a label, and if it is a text style Button, you can set the font of this text.

The syntax format of Button is as follows.

Button(master, options, ...)

In the window component, you can design the Button to perform a specific action when you click on it. This action is also called callback method, which means that we can use the Button as a bridge between the user and the program.

Button can have text on it, or it can have an image like a label, and if it is a text style Button, you can set the font of this text.

The syntax format of Button is as follows:

(1) borderwidth or bd: the border width is two pixels by default.

(2) bg or background: the background color.

(3) command: the method is executed when the function button is clicked.

(4) cursor: the shape of the button when the mouse cursor is moved over it.

(5) fg or foreground: the foreground color.

(6) font: the font shape.

(7) height: height, in character height.

(8) highlightbackground: the background color when the function button gets the focus.

(9) highlightcolor: the color of the function button when it gets the focus.

(10) image: the image on the function button.

(11) justify: when there are multiple lines of text, the alignment of the last line of text.

(12) padx: default is 1, which can set the interval between function button and text.

(13) pady: default is 1, you can set the spacing between the top and bottom of the function buttons.

(14) relief: the default is relief=FLAT, which can control the outer frame of the text.

(15) state: the default is state=NORMAL, if set to DISABLED, the function button will be displayed in gray scale, indicating that it is temporarily unavailable.

(16) text: the name of the function button.

(17) underline: you can set the first text with underline, starting from 0, the default is -1 means no underline.

(18) width: width, the unit is the character width.

(19) wraplength: limit the number of text per line, the default is 0, which means only "\n" will be a new line.

Tkinter Button Example#1

The string I love Python is displayed when the Button is clicked, with a light yellow background and a blue string color.

from tkinter import * 

cnt=1
def msgShow():
    global cnt
    label["text"] = "I love Python x" + str(cnt)
    label["bg"] = "lightyellow"
    label["fg"] = "blue"
    # label.config(text="I love Python x" + str(cnt),
    #         bg="lightyellow",fg="blue")
    cnt += 1

root = Tk()
root.title("apidemos.com")
label = Label(root)
# label["text"] = "I love python"
btn = Button(root,text="Print Message",command=msgShow)
label.pack()
btn.pack()

root.mainloop()

Output:

Tkinter Button Tutorial

After click Print Message:

Tkinter Button Tutorial

The above program runs as the program is executed:

  • Line 15 creates a Label object with no attributes

  • A Button is created on line 17.

When the Print Message button is clicked, the msgShow function is started, and then this function is executed to set the content of the label object label.

In the Python Tkinter Label article when we learn Label, we use the Label( ) method to set all the properties at once, and later readers can refer to lines 6 to 8 to set the property contents separately.

We have learned the config( ) method in Tkinter Widget config() Method. ) method, you can also use the method in that section to set all the widget control properties at once.

Tkinter Button Example#2

Use the config() method to set all widget control properties.

from tkinter import * 

cnt=1
def msgShow():
    global cnt
    # label["text"] = "I love Python x" + str(cnt)
    # label["bg"] = "lightyellow"
    # label["fg"] = "blue"
    label.config(text="I love Python x" + str(cnt),
            bg="lightyellow",fg="blue")
    cnt += 1

root = Tk()
root.title("apidemos.com")
label = Label(root)
# label["text"] = "I love Python"
btn = Button(root,text="Print Message",command=msgShow)
label.pack()
btn.pack()

root.mainloop()

Output:

Tkinter Button Tutorial

After click Print Message:

Tkinter Button Tutorial

Tkinter Button Example#3

If you click the Close button, the window can be closed.

from tkinter import * 

cnt=1
def msgShow():
    global cnt
    # label["text"] = "I love Python x" + str(cnt)
    # label["bg"] = "lightyellow"
    # label["fg"] = "blue"
    label.config(text="I love Python x" + str(cnt),
            bg="lightyellow",fg="blue")
    cnt += 1

root = Tk()
root.title("apidemos.com")
label = Label(root)
# label["text"] = "I love Java"
btn1 = Button(root,text="Print Message",width=15,command=msgShow)
btn2 = Button(root,text="Close",width=15,command=root.destroy)
label.pack()
btn1.pack(side=LEFT)
btn2.pack(side=LEFT)

root.mainloop()

Output:

Tkinter Button Tutorial

After click Print Message:

Tkinter Button Tutorial

root.destroy on line 18 above closes the root window object while the program ends.

Another common method is quit, which allows the program executing inside the Python Shell to end, but the root window to continue executing, as will be explained later in this example.

Tkinter Button Example#4

Design a timer program, add the End button, and click the End button to end the program execution.

from tkinter import *

counter = 0                                # Global Variables for Counting
def run_counter(digit):                    # Update of digital variable content   
    def counting():                        # Update digital method
        global counter                     # Define global variables
        counter += 1                       
        digit.config(text=str(counter))    # List digital content
        # counter += 1
        digit.after(1000,counting)         # Call counting after one second
    counting()                             # Continuous call

root = Tk()
root.title("apidemos.com")

digit = Label(root,bg="yellow",fg="blue",
                height=3,width=10,
                font="Helvetic 20 bold") 
digit.pack()   
run_counter(digit)   
Button(root,text="End",width=15,command=root.destroy).pack(pady=10)  
root.mainloop()

Output:

Tkinter Button Tutorial

Tkinter Button Example#5

There are three buttons in the lower right corner of the window. Click the Yellow button to set the window background to yellow, click the Blue button to set the window background to blue, and click the Exit button to end the program.

from tkinter import *

def yellow():
    root.config(bg="yellow")
def blue():
    root.config(bg="blue")

root = Tk()
root.title("apidemos.com")
root.geometry("300x200")
# Create three new buttons with this
exitbtn = Button(root,text="Exit",command=root.destroy)
bluebtn = Button(root,text="Blue",command=blue)
yellowbtn = Button(root,text="Yellow",command=yellow)
# Position the three button packs at the bottom right
exitbtn.pack(anchor=S,side=RIGHT,padx=5,pady=5)
bluebtn.pack(anchor=S,side=RIGHT,padx=5,pady=5)
yellowbtn.pack(anchor=S,side=RIGHT,padx=5,pady=5)

root.mainloop()

Output:

Tkinter Button Tutorial

Like(1)
Python Tkinter Tutorial
Python Tkinter tutorialTkinter Create WindowTkinter Window propertiesTkinter Window positionTkinter Widget IntroductionTkinter Widget Common PropertiesTkinter Widget Common MethodTkinter Widget Foreground ColorTkinter Widget DimensionsTkinter Widget AnchorTkinter Widget FontTkinter Widget Bitmaps PropertyTkinter Widget compound ParameterTkinter Widget reliefTkinter PhotoImageTkinter Widget config() MethodTkinter Widget Cursors PropertyTkinter Widget keys() MethodTkinter SeparatorTkinter Variable Basic conceptsTkinter Variable get() and set()Tkinger variable trace() using w modeTkinter variable trace() using r modeTkinter trace() method callback ParametersTkinter variables Example - CalculatorTkinter Widget command parameter
Tkinter Label
Python Tkinter LabelTkinter Label wraplengthTkinter Label justify ParameterTkinter Label Padding
Tkinter Widget Layout Manager
Tkinter Widget Layout ManagerTkinter pack side parameterTkinter pack padx/pady parameterTkinter pack ipadx/ipady parameterTkinter pack anchor parameterTkinter pack fill parameterTkinter pack expand parameterTkinter pack methodTkinter grid row and columnTkinter grid columnspan parameterTkinter grid rowspan parameterTkinter grid padx and pady parameterTkinter grid sticky parameterTkinter grid method exampleTkinter grid rowconfigure() and columnconfigure()Tkinter place x/y parameterTkinter place width/height parameterTkinter place relx/rely and relwidth/relheight parameter
Tkinter Button
Tkinter Button TutorialTkinter Button Lambda ExpressionTkinter Button with an imageTkinter Button Implement a simple calculatorTkinter Cursor shape on Button
Tkinter Entry
Tkinter Entry TutorialTkinter Entry Show ParameterTkinter Entry get() MethodTkinter Entry insert() MethodTkinter Entry delete() MethodTkinter eval calculates mathematical expressions
Tkinter Radiobutton
Tkinter Radiobutton TutorialTkinter Radiobutton with DictionaryTkinter Box RadiobuttonTkinter Radiobutton with Image
Tkinter Checkbutton
Tkinter Checkbutton TutorialTkinter Checkbutton Example
Tkinter Frame
Tkinter Frame TutorialTkinter Create widget inside FrameTkinter Frame relief propertiesTkinter Create Checkbuttonin FrameTkinter Frame relief attribute additional supportTkinter LabelFrame TutorialTkinter add Checkbutton in LabelFrameTinker Toplevel TutorialTkinter Simulation dialog using Toplevel window
Tkinter Scale
Tkinter Scale BasicTkinter get and set the Scale value of ScaleTkinter Scale Set Window Background ColorTkinter colorchooser askcolor() MethodTkinter Frame and Scale integrated Example
Tkinter Spinbox
Tkinter Spinbox TutorialTkinter Spinbox get methodTkinter stores Spinbox's numerical data in sequenceTkinter Spinbox uses non-numeric data
Tkinter Message
Tkinter Message TutorialTkinter Message Handling text parameters with string variablesTkinter Messagebox Tutorial
Tkinter Event
Tkinter Event BindTkinter mouse binding basic usageTkinter keyboard binding basic usageTkinter Keyboard and mouse event binding pitfallsTkinter Event unbindTkinter Binding multiple event handlers to single eventTkinter Protocols
Tkinter ListBox
Tkinter ListBox TutorialTkinter ListBox insert() MethodTkinter Listbox Basic OperationTkinter ListBox Item CountTkinter ListBox selects specific index itemsTkinter ListBox Delete specific index itemsTkinter ListBox Pass back the specified index itemTkinter ListBox Return the index of the selected itemTkinter ListBox check if the specified item is selectedTkinter ListBox Virtual binding applied to radio selectionTkinter ListBox Virtual binding applied to multiple choicesTkinter ListBox Add and Delete ItemTkinter Listbox Order ItemsTkinter Drag and drop the items in the ListboxTkinter Scrollbar in Listbox
Tkinter OptionMenu
Tkinter OptionMenu TutorialTkinter OptionMenu Create items with tupleTkinter OptionMenu Create default optionTkinter OptionMenu Get option content
Tkinter Combobox
Tkinter Combobox TutorialTikinter Combobox Set default optionTkinter Combobox Get current optionTkinter Bind Combobox
Tkinter PanedWindow
Tkinter PanedWindow TutorialTkinter PanedWindow Insert Child ObjectTkinter PanedWindow Create LabelFrame as child objectTkinter PanedWindow weight parameterTkinter Insert different controls in PanedWindow
Tkinter Notebook
Tkinter Notebook TutorialTkinter Notebook Bind tabs to child control content
Tkinter Progressbar
Tkinter Progressbar TutorialTkinter Progressbar AnimationTkinter Progressbar start/step/stop MethodTkinter Progressbar Indeterminate Mode
Tkinter Menu
Tkinter Menu TutorialTkinter Menu tearoff ParameterTkinter Menu Add separator between listsTkinter Menu Create multiple menu applicationsTkinter Menu Alt shortcutTkinter Menu Ctrl+ShortcutsTkinter Menu Create submenuTkinter Menu Create pop-up menuTkinter Menu add_checkbuttonTkinter Menu Create Toolbar
Tkinter Text
Tkinter Text TutorialTkinter Text Insert textTkinter Text Add Scrollbar designTkinter Text family ParameterTkinter Text weight ParameterTkinter Text size ParameterTkinter Text Select textTkinter Text’s indexTkinter Text Create MarksTkinter Text TagsTkinter Text Cut/Copy/Paste FunctionTkinter Text Undo and RedoTkinter Text Find TextTkinter Text Spell CheckTkinter Store Text Control ContentTkinter Text New DocumentTkinter Open DocumentTkinter Default ScrolledText control with scrollbarsTkinter Text Insert Image
Tkinter Treeview
Tkinter Treeview TutorialTkinter Format content of Treeview fieldsTkinter Treeview Create row content in different colorsTkinter Create a hierarchical TreeviewTkinter Treeview Insert ImageTkinter Treeview Selection Option Occurrence and Event TriggerTkinter Treeview Delete ItemTkinter Treeview Insert ItemTkinter Treeview Double-click an itemTkinter Treeview Bind scrollbarTkinter Treeview Sorting
Tkinter Canvas
Tkinter Canvas Draw linesTkinter Canvas Draw RectangleTkinter Canvas Drawing arcsTkinter Canvas Drawing circles or ellipsesTkinter Canvas Draw polygonTkinter Canvas Output TextTkinter Canvas Change the background colorTkinter Canvas Insert ImageTkinter Canvas Mouse dragging to draw linesTkinter Canvas Basic AnimationTkinter Canvas Design for multiple ball movementTkinter Canvas Applying random numbers to the movement of multiple spheresTkinter Canvas Message BindingsTkinter Canvas Design the ball to move downTkinter Canvas Designed to let the ball bounce up and downTkinter Canvas Design so that the ball bounces on all sides of the canvasTkinter Canvas Build racketTkinter Canvas Design racket movementTkinter Canvas Handling of racket and ball collisionsTkinter Canvas Implementation of bouncing ball design game
Tkinter Examples
A Simple News App with Tkinter and NewsapiAdding coloured text to selected text in TkinterCall the same function when clicking a Button and pressing Enter in TkinterChanging the Background Color of a Tkinter Window using Colorchooser ModuleChanging Tkinter Label Text Dynamically using Label.configure()Combobox Widget in Python TkinterCopy from clipboard using Python and TkinterCreate a GUI to Check Domain Availability using TkinterCreating a GUI to Get Domain Information using TkinterCreating a LabelFrame inside a Tkinter CanvasCreating an Automatically Maximized Tkinter WindowDisplay the Host Name and IP Address on a Tkinter WindowEmbedding an Image in a Tkinter Canvas Widget using PILGet the value from a Tkinter scale and put it into a LabelGetting the Cursor Position in Tkinter Entry WidgetHow can I determine the position of a Toplevel in Tkinter?How do I open a website in a Tkinter window?How do I position the buttons on a Tkinter window?How to Add a Column to a Tkinter TreeView Widget?How to Add PDF in Tkinter GUI Python?How to attach a vertical scrollbar to a Treeview using Tkinter?How to Bind a Tkinter Event to the Left Mouse Button Being Held Down?How to Bind all the Number Keys in TkinterHow to Bring a Dialog Box to Appear at the Front in a Tkinter Module of Python?How to call a function using the OptionMenu widget in Tkinter?How to Center a Label in a Frame of Fixed Size in Tkinter?How to Change the Background Color of a Tkinter Canvas Dynamically?How to Clear the Text Field Part of ttk.Combobox in Tkinter?How to close only the TopLevel window in Python Tkinter?How to create an impressive GUI in Python using Tkinter?How to Directly Modify a Specific Item in a TKinter ListboxHow to disable an Entry widget in Tkinter?How to disable multiselection on Treeview in tkinter?How to Display a Tkinter Application in Fullscreen on macOS?How to display multiple labels in one line with Python Tkinter?How to Draw a Dashed Line on a Tkinter Canvas?How to draw a line following mouse coordinates with tkinter?How to Draw an Arc on a Tkinter Canvas?How to exit from Python using a Tkinter Button?How to Explicitly Resize Frames in Tkinter?How to Get a New API Response in a Tkinter Textbox?How to get a string from a tkinter filedialog in Python 3?How to get an Entry box within a Messagebox in Tkinter?How to get rid of widget border in Tkinter?How to get the index of selected option in Tkinter Combobox?How to Highlight a Tkinter Button in macOS?How to insert a temporary text in a tkinter Entry widget?How to make a new folder using askdirectory dialog in Tkinter?How to Make Specific Text Non-Removable in Tkinter?How to Place an Image into a Frame in Tkinter?How to Place Objects in the Middle of a Frame using TkinterHow to place the text at the center of an Entry box in Tkinter?How to put a border around a Frame in Python Tkinter?How to Resize an Entry Box by Height in Tkinter?How to run an infinite loop in Tkinter?How to save the contents of a Textbox in Tkinter?How to set a certain number of rows and columns of a Tkinter grid?How to set a default string value on a Tkinter Spinbox?How to Set Padding of All Widgets Inside a Window or Frame in Tkinter?How to Show Multiple Canvases at the Same Time in TkinterHow to Show the Status of CAPS Lock Key in Tkinter?How to Specify the File Path in a Tkinter Filedialog?How to stop copy, paste, and backspace in text widget in tkinter?How to stop Tkinter Message widget from resizing?How to take input in a text widget and display the text in tkinter?How to Temporarily Remove a Tkinter Widget without Using just .placeHow to Update a Button Widget in Tkinter?How to Use a StringVar Object in an Entry Widget in Tkinter?Printing a List to a Tkinter Text WidgetPython Tkinter How to display a table editor in a text widget?Python Tkinter : How to export data from Entry Fields to a CSV file?Python Tkinter ŌĆō How to Position a topLevel() Widget Relative to the Root Window?Tkinter ŌĆō How to Create Colored Lines Based on Length?Tkinter-How to get the current date to display in a tkinter window?Tkinter - How to Put an Outline on a Canvas Text