Tkinter for Python GUI programming

 1. Introduction

Tkinter is one of the most commonly used GUI modules in Python, and it is the standard GUI library that comes with Python. Tkinter provides some UI controls, such as buttons, labels, text boxes, drop-down boxes, list boxes, scroll bars, etc., which can be used to create various GUI applications. Tkinter uses Tcl/Tk as the underlying graphics library, so it can run on multiple platforms.

We will introduce Tkinter from five aspects: installation and environment configuration, basic controls, layout management, advanced controls, event handling, styles and themes according to functional division. Finally, an example of a calculator is given to consolidate these knowledge points.

2. Installation and environment configuration

In Python 2.x versions, Tkinter's name is Tkinter; in Python 3.x versions, Tkinter's name is tkinter. Because Tkinter is a standard library of Python, no additional installation is generally required. If you need to install Tkinter, you can use the following command:

bash
# Ubuntu/Debiansudo apt-get install python3-tk
# CentOS/RHEL
sudo yum install python3-tkinter
# macOS

3. Basic controls

Tkinter provides some basic controls that can be used to create various GUI applications. Here are some common basic controls:

control name

Function

control name

Function

Label

for displaying text or images

Entry

for entering a single line of text

Button

for triggering events

Text

for entering multiple lines of text

Checkbutton

Used to select one or more options

Scale

Used to select a range of values

Radiobutton

Used to select an option

Listbox

for display list

Combobox

Used to display a drop-down list

Each control has some properties, methods and events, which can be studied in depth through official documents or other materials. Here is an example using basic controls:

import tkinter as tk

root = tk.Tk()
root.title("My Window")
root.geometry("300x200")

# 添加Label
label = tk.Label(root, text="Hello, Tkinter!")
label.pack()

# 添加Button
def button_click():
    print("Button clicked!")

button = tk.Button(root, text="Click me!", command=button_click)
button.pack()

# 添加Entry
entry = tk.Entry(root)
entry.pack()

# 添加Text
text = tk.Text(root)
text.pack()

# 添加Checkbutton
checkbutton_var = tk.BooleanVar()
checkbutton_var.set(False)
checkbutton = tk.Checkbutton(root, text="Check me!", variable=checkbutton_var)
checkbutton.pack()

# 添加Radiobutton
radiobutton_var = tk.StringVar()
radiobutton_var.set("Option 1")
radiobutton1 = tk.Radiobutton(root, text="Option 1", variable=radiobutton_var, value="Option 1")
radiobutton2 = tk.Radiobutton(root, text="Option 2", variable=radiobutton_var, value="Option 2")
radiobutton1.pack()
radiobutton2.pack()

# 添加Scale
scale_var = tk.DoubleVar()

4. Layout management

Layout management is a very important part when we create GUI applications in Tkinter. Layout managers are used to place controls in the window and determine their position and size. Tkinter provides three main layout managers: Pack, Grid, and Place.

Pack layout manager is one of the simplest layout managers. It places the controls in the window in the order they were added. The Pack layout manager has three main options:

  1. side: The placement direction of the control, which can be TOP, BOTTOM, LEFT or RIGHT.
  2. fill: The filling method of the control, which can be NONE, X, Y or BOTH.
  3. expand: Whether the control is expanded, which can be True or False.

For example, the following code will create two Button controls, one at the top and one at the bottom, and both expand to the width of the window.

import tkinter as tk

root = tk.Tk()

button1 = tk.Button(root, text="Button 1")
button1.pack(side="top", fill="both", expand=True)

button2 = tk.Button(root, text="Button 2")
button2.pack(side="bottom", fill="both", expand=True)

root.mainloop()

The Grid layout manager is a two-dimensional grid layout that places controls at the intersection of rows and columns. You can easily use the Grid layout manager for layout by specifying the row and column in which the control resides.

For example, the following code will create three Label controls, which are placed in the first column of the first row, the first column of the second row, and the second column of the second row.

import tkinter as tk

root = tk.Tk()

label1 = tk.Label(root, text="Label 1")
label1.grid(row=0, column=0)

label2 = tk.Label(root, text="Label 2")
label2.grid(row=1, column=0)

label3 = tk.Label(root, text="Label 3")
label3.grid(row=1, column=1)

root.mainloop()

The Place layout manager is a very flexible layout manager that allows you to precisely specify the position and size of controls. The Place layout manager has two main options: x and y, which specify the coordinates of the upper-left corner of the control.

For example, the following code will create a Label control and place it in the center of the window:

import tkinter as tk

root = tk.Tk()

label = tk.Label(root, text="Hello, Tkinter!")
label.place(relx=0.5, rely=0.5, anchor="center")

5. Advanced controls

Tkinter provides some advanced controls that can be used to create more complex and rich GUI applications. This section will introduce Canvas, Listbox, Treeview and Menu controls.

1. Canvas

The Canvas control is a vector graphics editor that can be used to draw graphics, text and bitmaps. It provides methods and tools to create complex graphical effects.

Properties of the Canvas Control

effect

Methods of the Canvas control

effect

background

background color

create_arc()

create arc

bd

border width

create_bitmap()

create bitmap

relief

border style

create_line()

create lines

width

width

create_oval()

create ellipse

height

high

create_polygon()

create polygon

create_rectangle()

create rectangle

create_text()

create text

import tkinter as tk

root = tk.Tk()
root.title("Canvas Example")
root.geometry("300x200")

canvas = tk.Canvas(root, bg="white", width=200, height=100)
canvas.pack()

# 创建椭圆
canvas.create_oval(50, 20, 150, 80, fill="yellow")

# 创建文本
canvas.create_text(100, 50, text="Hello, Canvas!", font=("Arial", 14))

root.mainloop()

2. Listbox

The Listbox control is a list box that can be used to display a set of items and allow the user to select one or more of the items. It provides methods and events to handle the items in the list box.

Properties of the Listbox control

effect

Methods of the Listbox control

effect

background

background color

insert()

insert item

bd

border width

delete()

delete item

relief

border style

get()

get item

selectbackground

Select background color

activate()

activate project

selectmode

select mode

courseselection()

Get the subscript of the currently selected item

import tkinter as tk

root = tk.Tk()
root.title("Listbox Example")
root.geometry("300x200")

listbox = tk.Listbox(root, bg="white", selectmode=tk.MULTIPLE)
listbox.pack()

# 添加项目
listbox.insert(1, "Item 1")
listbox.insert(2, "Item 2")
listbox.insert(3, "Item 3")

root.mainloop()

3. Treeview

The Treeview control is a tree list box that can be used to display hierarchical data. It provides some methods and events to handle the data in the tree list box.

Properties of the Treeview control

effect

Methods of the Treeview control

effect

columns

column name

insert()

insert data

displaycolumns

show column names

delete()

delete data

height

high

item()

retrieve data

selectmode

select mode

selection()

Get the currently selected data

import tkinter as tk
import tkinter.ttk as ttk

root = tk.Tk()
root.title("Treeview Example")
root.geometry("300x200")

treeview = ttk.Treeview(root, columns=("Name", "Age"))

6. Event handling

Event is an important concept in Tkinter, which represents various actions generated by the user's interaction with the application, such as mouse clicks, keyboard input, window resizing, and so on. Tkinter provides an event handling mechanism, which can handle events by binding events and callback functions.

1. Binding  events

The way to bind an event is to call the bind() method on the control, for example:

python
button = tk.Button(root, text="Click me!")
button.bind("<Button-1>", button_click)

Among them, the first parameter is the name of the event, and the second parameter is the callback function. Event names can be various events such as mouse clicks, keyboard input, window resizing, and so on. The callback function is a function that is called automatically when an event occurs, and it can obtain relevant information about the event, such as mouse position, keyboard input, event type, and so on. You can use the bind() method to bind the same callback function for multiple events, for example:

python
entry = tk.Entry(root)
entry.bind("<Return>", entry_submit)
entry.bind("<FocusIn>", entry_focus_in)
entry.bind("<FocusOut>", entry_focus_out)

The above code binds three events for a text box, which are enter key input, focus gain and focus loss. For each event, a different callback function is called.

2. Callback  function

The callback function is a function that is called automatically when an event occurs, and it can obtain relevant information about the event, such as mouse position, keyboard input, event type, and so on. The callback function can be defined as a normal function or a lambda expression, for example:

python
def button_click(event):
    print("Button clicked!")
    
entry.bind("<Return>", lambda event: entry_submit(event, arg1, arg2))

Among them, event is an event object, which can be used to obtain related information of the event. Lambda expressions can take additional arguments, such as arg1 and arg2.

3.  Event Type

Tkinter supports various event types such as:

  1. Mouse events: Button-1, Button-2, Button-3, Double-Button-1, Double-Button-2, Double-Button-3, Motion, Enter, Leave, etc.
  2. Keyboard events: KeyPress, KeyRelease, etc.
  3. Window events: Configure, Activate, Deactivate, etc.
  4. Other events: FocusIn, FocusOut, Timer, VirtualEvent, etc.

All supported event types and detailed descriptions can be viewed in the official documentation.

4.  Example _

Here is a simple example showing how to use the event handling mechanism:

python
import tkinter as tk

def button_click(event):
    print("Button clicked!")

def entry_submit(event):
    print("Entry submitted:", event.widget.get())

root = tk.Tk()
root.title("Event Handling")
root.geometry("300x200")

# 添加按钮
button = tk.Button(root, text="Click me!")
button.bind("<Button-1>", button_click)
button.pack()

# 添加文本框
entry = tk.Entry(root)
entry.bind("<Return>", entry_submit)
entry.pack()

root.mainloop()

The above code creates a window containing a button and a textbox. When the user clicks the button, the callback function button_click() will be called. When the user enters the Enter key in the text box, the callback function entry_submit() will be called to output the content in the text box.

7. Styles and themes

1. Style

Style is the appearance and style of the control in Tkinter, you can change its appearance by setting the style of the control. Tkinter provides a style manager that can be used to manage and apply styles.

Here is an example of using styles:

python
import tkinter as tkfrom tkinter import ttk

root = tk.Tk()
# 创建样式
style = ttk.Style(root)
style.configure("My.TButton", font=("Helvetica", 14))
# 添加按钮
button = ttk.Button(root, text="Click me!", style="My.TButton")
button.pack()

root.mainloop()

In the above example, first create a style manager, and use the configure() method to set a style named "My.TButton", which sets the font of the button as Helvetica 14 point. Then I created a button and set its style to "My.TButton".

2. Theme

A theme is a collection of colors and appearances of controls in Tkinter. You can change the colors and appearances of all controls by setting a theme. Tkinter provides some built-in themes, and you can also customize themes. Here is an example of using a theme:

python
import tkinter as tkfrom tkinter import ttk

root = tk.Tk()
# 设置主题
style = ttk.Style()
style.theme_use("clam")
# 添加按钮
button = ttk.Button(root, text="Click me!")
button.pack()

root.mainloop()

In the above example, a style manager is first created and the theme is set to "clam" using the theme_use() method. Then created a button which uses the default styles from the theme. You can learn more about styles and themes by looking at the official Tkinter documentation or other resources.

Eight, actual combat items: a calculator.

1. Demand

Realize a simple calculator that can perform four basic operations of addition, subtraction, multiplication, and division, and supports decimal and negative operations.

2. Implementation method

2.1  Interface design

Use the layout manager in Tkinter to realize the interface layout of the calculator, including a text box and multiple buttons.

import tkinter as tk

class Calculator:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("Calculator")
        
        # 创建文本框
        self.textbox = tk.Entry(self.root, width=30, font=("Arial", 16))
        self.textbox.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
        
        # 创建按钮
        self.create_button("7", 1, 0)
        self.create_button("8", 1, 1)
        self.create_button("9", 1, 2)
        self.create_button("/", 1, 3)
        self.create_button("4", 2, 0)
        self.create_button("5", 2, 1)
        self.create_button("6", 2, 2)
        self.create_button("*", 2, 3)
        self.create_button("1", 3, 0)
        self.create_button("2", 3, 1)
        self.create_button("3", 3, 2)
        self.create_button("-", 3, 3)
        self.create_button("0", 4, 0)
        self.create_button(".", 4, 1)
        self.create_button("C", 4, 2)
        self.create_button("+", 4, 3)
        self.create_button("=", 5, 0, columnspan=4)

    def create_button(self, text, row, column, rowspan=1, columnspan=1):
        button = tk.Button(self.root, text=text, width=7, height=2, font=("Arial", 16))
        button.grid(row=row, column=column, rowspan=rowspan, columnspan=columnspan, padx=5, pady=5)
        
    def run(self):
        self.root.mainloop()

if __name__ == "__main__":
    calculator = Calculator()
    calculator.run()

2.2 Realize the calculation function

Implement the calculation function in the event processing function of the button, and use the eval function to calculate the value of the expression.

import tkinter as tk

class Calculator:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("Calculator")
        
        # 创建文本框
        self.textbox = tk.Entry(self.root, width=30, font=("Arial", 16))
        self.textbox.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
        
        # 创建按钮
        self.create_button("7", 1, 0)
        self.create_button("8", 1, 1)
        self.create_button("9", 1, 2)
        self.create_button("/", 1, 3)
        self.create_button("4", 2, 0)
        self.create_button("5", 2, 1)
        self.create_button("6", 2, 2)
        self.create_button("*", 2, 3)
        self.create_button("1", 3, 0)
        self.create_button("2", 3, 1)
        self.create_button("3", 3, 2)
        self.create_button("-", 3, 3)
        self.create_button("0", 4, 0)
        self.create_button(".", 4, 1)
        self.create_button("C", 4, 2)
        self.create_button("+", 4, 3)
        self.create_button("=", 5, 0, columnspan=4, command=self.calculate)

    def create_button(self, text, row, column, rowspan=1, columnspan=1, command

Guess you like

Origin blog.csdn.net/mnbey/article/details/131037349