SoFunction
Updated on 2025-05-06

Brief tutorial on tkinter in python (must read by novice)

1. Tkinter Overview and Features

1.1 Core positioning

Tkinter is a standard GUI library for Python, encapsulated based on the Tcl/Tk toolkit. It has the following characteristics:

  • Cross-platformity: Supports Windows, Linux and macOS systems.
  • Lightweight: No additional installation required, as a built-in module for Python, it works out of the box.
  • Development efficiency: Concise syntax, suitable for rapid development of prototypes and small applications.

1.2 Applicable scenarios

Tkinter is suitable for small and medium-sized desktop application development, such as data display tools, configuration management interfaces, teaching demonstration programs, etc. For complex 3D rendering or high-performance scenarios, it is recommended to use PyQt or PySide.

Summarize:Tkinter is characterized by simple, lightweight and efficient, but its functions are relatively basic and the interface is relatively simple. For more complex interface development, consider using PyQt 6.

2. Development environment preparation

When using Tkinter, you usually need to import the following modules:

import tkinter as tk  # Basic modulefrom tkinter import ttk  # Provide modern style controls

3. Core component analysis

3.1 Main window architecture

Here is a code example for creating a basic Tkinter window:

root = ()
("Apply Title")  # Set window title("800x600+100+100")  # Set window size and position: width x height + X offset + Y offset(bg="#F0F0F0") # Set background color()  # Start the event loop

Key Methods

  • resizable(width, height): Set whether the window can be resized. For example,resizable(0, 0)It is prohibited to resize the window.
  • attributes('-alpha', value): Set window transparency (between 0 and 1).
  • iconbitmap(''): Modify the window icon (Windows system).

Notice: The coordinate origin of Tkinter is located in the upper left corner of the screen.

3.2 Common control library

The following are commonly used controls and their core properties in Tkinter:

Control Type Function description Core attribute examples
Label Static text display textfontfgbg
Button Trigger action (button) commandstateNORMAL/DISABLED
Entry Single-line text input show(Password mask),validatecommand
Text Multi-line rich text editing insert()delete()tagsConfiguration
Canvas Drawing and custom control containers create_linecreate_ovalcreate_rectangle
Listbox List selection selectmodeMULTIPLE/EXTENDED
Combobox Pull down to select (ttkModule) valuescurrent()

3.3 Layout Manager Comparison

Tkinter provides three layout managers to control how controls are arranged. Selecting the right layout manager can simplify interface development.

🟢(1)pack()Layout Manager

pack()It is a layout method that automatically arranges controls in order, suitable for simple layouts. It arranges the control into the parent container according to the order in which it is added.

(side=, fill=, padx=10)
  • side: Specify the direction of the control arrangement ()。
  • fill: Specify how the control is filled in the allocated space ()。
  • expand: Specifies whether the control can be expanded to fill additional space (TrueorFalse)。
  • anchor: Specify the alignment direction of the control ()。
  • padx/pady: Specifies the horizontal and vertical margins between the control and the parent container.

🟢 (2)grid()Layout Manager

grid()It is a table-based layout method suitable for scenarios where control positions need to be accurately controlled.

(row=0, column=0, sticky="ew", columnspan=2)
  • row/column: Specify the row and column where the control is located.
  • sticky: Specifies how the control "adhes" to the cells it allocated ("n""s""e""w""ew""ns""nsew")。
  • rowspan/columnspan: Specifies the number of rows or columns that the control spans.
  • padx/pady: Specifies the horizontal and vertical margins between the control and the cell.
  • rowconfigure/columnconfigure: Set weights for rows or columns to control their expansion ratio when the window is resized.

🟢 (3) place() Layout Manager

place()It is a layout method based on absolute or relative coordinate positioning, suitable for scenarios where pixel-level control is required.

(relx=0.5, rely=0.5, anchor=)
  • x/y: Specifies the absolute coordinates of the control (in pixels).
  • relx/rely: Specifies the relative coordinates of the control (value ranges from 0 to 1).
  • anchor: Specify the anchor position of the control ()。
  • width/height: Specifies the width and height of the control in pixels.

Summarize

  • pack(): Suitable for simple layouts, quickly arrange controls in order.
  • grid(): Suitable for scenarios that require table and precise control of layout.
  • place(): Suitable for scenes where precise control position is required, such as pixel-level positioning.

IV. Event handling mechanism

4.1 Basic event binding

Event binding is an important concept in graphical user interface (GUI) programming, which allows users to trigger specific operations through input devices such as mouse, keyboard, etc. In Tkinter, event binding passesbind()Method implementation can correlate user operations with corresponding processing functions.

# Create a button and trigger the submit function when clickedbutton = (root, text="submit", command=submit)

# Bind the left mouse button click event to the canvas and trigger the draw function("<Button-1>", lambda e: draw(, ))

# Bind the Enter key event to the entry and trigger the process_input function("<Return>", process_input)

Parameter explanation

  • command parameters (button event)

    • commandyesA parameter for binding button click event. When the button is clicked, the specified function is called. For example,command=submitIndicates that it is called when clicking the buttonsubmit()Function.
  • bind()Method (general event binding)

    • bind()It is a method used in Tkinter to bind events, in the format:(event, handler)
    • event: Event identifier, used to specify the conditions for triggering the event (such as mouse clicks, keyboard keys, etc.).
    • handler: Event handling function, called when the event is triggered.
  • lambdaAnonymous functions

    • When binding the event,lambdaUsed to create an anonymous function to facilitate passing event parameters (such as mouse coordinates). For example,lambda e: draw(, )Indicates that when the event is triggered, calldraw()Function and event objecteofxandyAttributes are passed to the function.
  • Event handling function

    • Event handling functions usually need to receive an event object as a parameter, which contains the detailed information of the event (such as mouse position, key information, etc.). For example:

      def draw(x, y):
          print(f"Draw points:({x}, {y})")
      

4.2 Complete event types

In Tkinter, events are represented by specific identifiers that define the conditions that trigger the event. Here are some common event types and their trigger conditions:

Event identifier and trigger conditions:

Event Identifier Trigger condition Sample code
<Button-1> Press the left mouse button ("<Button-1>", lambda e: print(e))
<Button-2> Press the middle mouse button
<Button-3> Right-click the mouse
<B1-Motion> Hold down the left mouse button and move ("<B1-Motion>", lambda e: print(e))
<ButtonRelease-1> Release the left mouse button ("<ButtonRelease-1>", lambda e: print(e))
<Motion> Mouse movement ("<Motion>", lambda e: print(e))
<MouseWheel> Mouse scroll wheel swipe ("<MouseWheel>", lambda e: print(e))
<KeyPress> Press any key ("<KeyPress>", lambda e: print(e))
<KeyPress-A> Press the A key ("<KeyPress-A>", lambda e: print(e))
<KeyRelease> Release any key ("<KeyRelease>", lambda e: print(e))
<Return> Press Enter ("<Return>", lambda e: print(e))
<Escape> Press the Esc key ("<Escape>", lambda e: print(e))
<Configure> Window size changes ("<Configure>", lambda e: print(e))
<Enter> Mouse enters the control ("<Enter>", lambda e: print(e))
<Leave> Mouse leaves control ("<Leave>", lambda e: print(e))
<FocusIn> Controls get focus ("<FocusIn>", lambda e: print(e))
<FocusOut> Control loses focus ("<FocusOut>", lambda e: print(e))

Event object properties:

The event object contains detailed information about the event, and the following are some commonly used properties:

Attribute name describe Example Values
Horizontal coordinates of mouse events 100
Vertical coordinates of mouse events 200
Key name of key event "A""Return"
Character values ​​of key event "a""\n"
Mouse button number 1(Left button),3(Right-click)
The scrolling volume of the mouse wheel 120(Scroll up)
The width of the window size changed 800
The height of the window size changes 600

Example: Complete Event Binding

Here is a complete example showing how to bind multiple events and handle them:

import tkinter as tk

def on_click(event):
    print(f"Click on the left mouse button:({}, {})")

def on_move(event):
    print(f"Move the mouse to:({}, {})")

def on_key_press(event):
    print(f"button:{}")

def on_resize(event):
    print(f"The window size is resized to:{}x{}")

root = ()
("400x300")

canvas = (root, bg="white")
(fill="both", expand=True)

# Bind the left mouse button click event("&lt;Button-1&gt;", on_click)

# Bind the mouse movement event("&lt;Motion&gt;", on_move)

# Bind keyboard key event("&lt;KeyPress&gt;", on_key_press)

# Bind window size change event("&lt;Configure&gt;", on_resize)

()

5. Advanced development skills

5.1 ttk theme customization

ttkThe module provides modern-style controls and supports theme customization. pass, can modify the appearance and behavior of the control.

style = ()
style.theme_use('clam')  # Use predefined topics (such as 'clam', 'alt', 'default', etc.)('TButton', padding=6, relief="flat")  # Customize button style('TEntry', foreground=[('disabled', 'gray')])  # Modify the disabled state color of the input box

5.2 Custom control development

By inheritanceor, you can create composite controls. Here is an example of a custom switch button:

class SwitchButton():
    def __init__(self, parent, *args, **kwargs):
        super().__init__(parent)
         = False
         = (self, width=60, height=30, bg="gray")
        ()
        self.draw_switch()
        ("<Button-1>", )

    def draw_switch(self):
        color = "green" if  else "red"
        .create_rectangle(10, 10, 50, 30, fill=color)

    def toggle(self, event):
         = not 
        self.draw_switch()

5.3 Multi-window interaction

In Tkinter, you can useCreate multiple windows and realize interaction between windows.

class SettingsWindow():
    def __init__(self, parent):
        super().__init__(parent)
        (parent)  # Associate the parent window        self.grab_set()  # Set as modal window        ("set up")
        ("300x200")
        (self, text="Here is the settings window").pack()

5.4 Asynchronous processing

In Tkinter apps, long-running tasks can cause interfaces to get stuck. passthreadingModule, time-consuming operations can be placed in the background thread to execute, avoiding blocking the main thread.

import threading

def long_task():
    # Simulate long-running tasks    import time
    (5)
    print("The mission is completed!")

def start_task():
    (target=long_task, daemon=True).start()

root = ()
button = (root, text="Start the mission", command=start_task)
()
()

5.5 Other Advanced Tips

5.5.1 Internationalization and localization

For applications that need to support multilingual, Tkinter provides international support. Can be passedandand other modules combine language packages to realize multilingual interface.

import tkinter as tk
from tkinter import messagebox

# Example: Multilingual Supportdef show_message():
    lang = ("Select a language", "Do you switch to English?")
    if lang:
        ("Message", "Hello, World!")
    else:
        ("information", "Hello World!")

root = ()
button = (root, text="Show Message", command=show_message)
()
()

5.5.2 Animation and dynamic interface

Tkinter supports itafterMethod to achieve simple animation effects. Here is a simple animation example:

import tkinter as tk

class AnimationApp:
    def __init__(self, root):
         = root
         = (root, width=400, height=300, bg="white")
        ()
         = .create_oval(10, 10, 50, 50, fill="red")
         = 5
         = 5
        ()

    def animate(self):
        (, , )
        coords = ()
        if coords[2] >= .winfo_width() or coords[0] <= 0:
             *= -1
        if coords[3] >= .winfo_height() or coords[1] <= 0:
             *= -1
        (50, )

if __name__ == "__main__":
    root = ()
    app = AnimationApp(root)
    ()

6. Project practical examples

Here is an example implementation of a simple text editor:

import tkinter as tk
from tkinter import ttk
from tkinter import filedialog

class TextEditor:
    def __init__(self, root):
         = root
        ("Easy Text Editor")
        ("800x600")

        # Create text area        self.text_area = (root, wrap="word", undo=True)
        self.text_area.pack(side="left", expand=True, fill="both")

        # Create scrollbar         = (root, command=self.text_area.yview)
        (side="right", fill="y")
        self.text_area.configure(yscrollcommand=)

        # Create menu        menubar = (root)
        file_menu = (menubar, tearoff=0)
        file_menu.add_command(label="Open", command=self.open_file)
        file_menu.add_command(label="save", command=self.save_file)
        menubar.add_cascade(label="document", menu=file_menu)
        (menu=menubar)

    def open_file(self):
        file_path = (filetypes=[("Text files", "*.txt"), ("All files", "*.*")])
        if file_path:
            with open(file_path, "r", encoding="utf-8") as file:
                content = ()
                self.text_area.delete("1.0", )
                self.text_area.insert("1.0", content)

    def save_file(self):
        file_path = (defaultextension=".txt", filetypes=[("Text files", "*.txt"), ("All files", "*.*")])
        if file_path:
            with open(file_path, "w", encoding="utf-8") as file:
                content = self.text_area.get("1.0", )
                (content)

if __name__ == "__main__":
    root = ()
    editor = TextEditor(root)
    ()

Summarize

This is all about this brief article about tkinter in python. For more related python tkinter tutorial content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!