Python | Creating a button in tkinter

Python Methods and Functions

Follow these steps:

  1. Import tkinter # Tkinter module into Python 2.x. (Capital T note)
  2. Create main window (root = Tk ())
  3. Add as many widgets as you like.

Import tkinter module is the same as importing any other module.

 import tkinter # In Python 3.x import Tkinter # In python 2.x. (Note Capital T) 

The tkinter.ttk module provides access to the Tk theme widget set introduced in Tk 8.5. If Python was not compiled with Tk 8.5, this module can be accessed if Tile was installed. The first method using Tk 8.5 provides additional benefits including rendering antialiased font in X11 and window transparency.

Main idea tkinter.ttk — If possible, separate the code that implements the behavior of the widget from the code that implements its appearance.  tkinter.ttk is used to create modern GUI applications that cannot be implemented by tkinter itself.

Code # 1 : Create a button using Tkinter.

# import everything from tkinter module

from tkinter import *  

 
# create tkinter window

root = Tk () 

  
# Open a 100x100 window

root.geometry ( `100x100`  

 
# Create button

btn = Button (root, text = `Click me!` , bd = `5` ,

  command = root.destroy) 

  
# Set the position of the button at the top of the window.

btn.pack ( side = `top`

 
root.mainloop ()

Output:

Create a button without using ok theme widget.
Create a button using the theme widget tk (tkinter.ttk). It will give you modern graphics effects. The effects will change from one OS to another because it`s mainly for the look.

Code # 2:

# import tkinter module

from tkinter import *  

  
# The following imports the tkinter.ttk module and
# automatically overrides all widgets
# which are present in the tkinter module.

from tkinter.ttk import * root = Tk () 

 
# Initialize 100x100 tkinter window

root.geometry ( `100x100`

  

btn = Button (root, text = ` Click me! ` ,

  command = root.destroy)

 
# Set the position of the button at the top of the window

btn.pack (side = `top`

  
root.mainloop ()

Output:

Note: look in the output of both codes, BORDER is not present in the 2nd output because tkinter.ttk does not support border. In addition, when you ttk.Button mouse cursor over both buttons, the ttk.Button button changes color and turns light blue (effects can change from one OS to another) because it supports modern graphics, while in the case of a simple button it will not change color since it does not support modern graphics.





Get Solution for free from DataCamp guru