How to Create Buttons with tkinter in Python


In this example, we will show how to create buttons and add them to frame with tkinter package. tkinter is the standard Python interface to the Tk GUI toolkit. With it, we can build various user interface.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# controlLayout.py

from tkinter import *

# the main window
win = Tk()

# the first window
frame1 = Frame(win, relief=RAISED, borderwidth=2)
frame1.pack(side=TOP, fill=BOTH, ipadx=10, ipady=10, expand=0)
Button(frame1, text="Button 1").pack(side=LEFT, padx=10, pady=10)
Button(frame1, text="Button 2").pack(side=LEFT, padx=10, pady=10)
Button(frame1, text="Button 3").pack(side=LEFT, padx=10, pady=10)

# the second window
frame2 = Frame(win, relief=RAISED, borderwidth=2)
frame2.pack(side=BOTTOM, fill=NONE, ipadx="1c", ipady="1c", expand=1)
Button(frame2, text="Button 4").pack(side=RIGHT, padx="1c", pady="1c")
Button(frame2, text="Button 5").pack(side=RIGHT, padx="1c", pady="1c")
Button(frame2, text="Button 6").pack(side=RIGHT, padx="1c", pady="1c")

# the third window
frame3 = Frame(win, relief=RAISED, borderwidth=2)
frame3.pack(side=LEFT, fill=X, ipadx="0.1i", ipady="0.1i", expand=1)
Button(frame3, text="Button 7").pack(side=TOP, padx="0.1i", pady="0.1i")
Button(frame3, text="Button 8").pack(side=TOP, padx="0.1i", pady="0.1i")
Button(frame3, text="Button 9").pack(side=TOP, padx="0.1i", pady="0.1i")

# the forth window
frame4 = Frame(win, relief=RAISED, borderwidth=2)
frame4.pack(side=RIGHT, fill=Y, ipadx="10p", ipady="10p", expand=1)
Button(frame4, text="Button 10").pack(side=BOTTOM, padx="10p", pady="10p")
Button(frame4, text="Button 11").pack(side=BOTTOM, padx="10p", pady="10p")
Button(frame4, text="Button 12").pack(side=BOTTOM, padx="10p", pady="10p")

# start window event loop
win.mainloop()

After running the codes above, we can see a frame with a list of buttons:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement