How to place a button at any position in Tkinter?
Prerequisite: Creating a button in Tkinter
Tkinter is the most commonly used library for developing GUI (Graphical User Interface) in Python. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using tkinter is an easy task.
Approach:
- Import the tkinter module
- Create the main window
- Add a button to the window.
- Place the button.
The button in the tkinter module can be placed or move to any position in two ways:
- By using the place() method.
- And by using the pack() method.
Method 1: Using the place() method
This method is used to place a button at an absolute defined position.
Syntax : button1.place(x=some_value, y=some_value)
Parameters :
- x : It defines the x-coordinate of the button’s position.
- y : It defines the y-coordinate of the button’s position.
Below is the implementation of the approach shown above:
Python3
# Importing tkinter module from tkinter import * # Creating a tkinter window root = Tk() # Initialize tkinter window with dimensions 300 x 250 root.geometry( '300x250' ) # Creating a Button btn = Button(root, text = 'Click me !' , command = root.destroy) # Set the position of button to coordinate (100, 20) btn.place(x = 100 , y = 20 ) root.mainloop() |
Output:
Method 2: Using the pack() method
This method is used to place a button at a relative position.
Syntax : button1.pack(side=some_side, padx=some_value, pady=some_value)
Parameters :
- side : It defines the side where the button will be placed.
- padx : It defines the padding on x-axis from the defined side.
- pady : It defines the padding on y-axis from that defines side.
Below is the implementation of the approach shown above:
Python3
# Importing tkinter module from tkinter import * # Creating a tkinter window root = Tk() # Initialize tkinter window with dimensions 300 x 250 root.geometry( '300x250' ) # Creating a Button btn = Button(root, text = 'Click me !' , command = root.destroy) # Set a relative position of button btn.pack(side = RIGHT, padx = 15 , pady = 20 ) root.mainloop() |
Output:
Contact Us