杰瑞科技汇

Python 3.3 tkinter如何入门?

Of course! Here is a comprehensive guide to using Tkinter with Python 3.3.

Python 3.3 tkinter如何入门?-图1
(图片来源网络,侵删)

Introduction: What is Tkinter?

Tkinter (short for "Tk Interface") is Python's standard and most commonly used library for creating graphical user interfaces (GUIs). It's a thin wrapper around the Tk GUI toolkit, which was originally designed for the Tcl programming language.

The key takeaway is that Tkinter comes built-in with Python. You don't need to install it separately, which makes it the perfect choice for beginners and for creating simple to moderately complex desktop applications.


A Simple "Hello, World!" Application

Let's start with the absolute basics. This code will create a window with a single button. When you click the button, it will print a message to the console.

# Import the Tkinter module (it's tkinter in Python 3)
import tkinter as tk
# 1. Create the main window
# The root window is the main container for all other widgets
root = tk.Tk()
# 2. Configure the window"My First App")      # Set the title of the window
root.geometry("300x200")        # Set the size of the window (width x height)
# 3. Create a widget (a button in this case)
# A button needs a parent to be placed in. Here, 'root' is the parent.
button = tk.Button(root, text="Click Me!", command=lambda: print("Hello, World!"))
# 4. "Pack" the widget into the window
# pack() is a simple geometry manager that places widgets in a block
button.pack(pady=20, padx=20) # Add some padding around the button
# 5. Start the event loop
# This line keeps the window open and listens for user events (like clicks)
root.mainloop()

To run this code:

Python 3.3 tkinter如何入门?-图2
(图片来源网络,侵删)
  1. Save it as a file (e.g., app.py).
  2. Open a terminal or command prompt.
  3. Navigate to the directory where you saved the file.
  4. Run the command: python app.py

You should see a window appear. Clicking the button will print "Hello, World!" to your terminal.


Core Concepts of Tkinter

Understanding these four concepts is essential to building any Tkinter application.

The Main Window (Tk)

This is the foundation of your application. Every GUI has one main window.

  • Creation: root = tk.Tk()
  • Configuration: Use methods like .title(), .geometry(), .configure() for background color, etc.

Widgets

Widgets are the components of your GUI: buttons, labels, text boxes, menus, etc.

  • Common Widgets:
    • tk.Label: Displays text or an image.
    • tk.Button: A clickable button.
    • tk.Entry: A single-line text entry field.
    • tk.Text: A multi-line text area.
    • tk.Frame: A container widget used to group other widgets.
    • tk.Canvas: For drawing shapes and graphics.
  • Creation: widget = tk.Widget(parent, options)

Geometry Managers

Geometry managers control how widgets are positioned and sized within their parent container. Tkinter has three main ones.

Manager Description Best For
pack() The simplest. It "packs" widgets one after another in a block. Good for simple layouts. Simple forms, toolbars, stacking widgets vertically or horizontally.
grid() Arranges widgets in a table-like structure of rows and columns. This is the most powerful and commonly used manager for complex forms. Forms, spreadsheets, any layout that aligns in rows and columns.
place() Allows you to place widgets at an exact x and y coordinate. This is the least flexible and can be brittle on window resizing. Absolute positioning, placing a small widget on top of another.

Example of grid():

import tkinter as tk
root = tk.Tk()"Grid Layout")
# Create widgets
label1 = tk.Label(root, text="Username:")
entry1 = tk.Entry(root)
label2 = tk.Label(root, text="Password:")
entry2 = tk.Entry(root, show="*") # Show * for password
# Use grid to place them
label1.grid(row=0, column=0, padx=5, pady=5)
entry1.grid(row=0, column=1, padx=5, pady=5)
label2.grid(row=1, column=0, padx=5, pady=5)
entry2.grid(row=1, column=1, padx=5, pady=5)
root.mainloop()

The Event Loop (mainloop())

This is the heart of a GUI application. It's an infinite loop that waits for events (like button clicks, key presses, or window closing) and calls the appropriate functions to handle them. Without root.mainloop(), your window would appear and immediately disappear.


A More Complete Example: A Simple Login App

Let's combine these concepts into a slightly more interactive application. This app will have a username, password, and a login button. When you click "Login," it will validate the input.

import tkinter as tk
from tkinter import messagebox # For showing pop-up messages
# --- Functions ---
def login():
    """Gets the text from the entry widgets and checks the credentials."""
    username = entry_username.get()
    password = entry_password.get()
    # Simple validation (in a real app, this would be a server check)
    if username == "admin" and password == "password123":
        messagebox.showinfo("Login", "Login Successful!")
    else:
        messagebox.showerror("Login Failed", "Invalid username or password.")
# --- Create the Main Window ---
root = tk.Tk()"Login Screen")
root.geometry("300x150")
# --- Create Widgets ---
# Frame to hold the form for better organization
form_frame = tk.Frame(root)
form_frame.pack(pady=10)
# Username
label_username = tk.Label(form_frame, text="Username:")
label_username.grid(row=0, column=0, padx=5, pady=5, sticky="e") # sticky="e" aligns to the east (right)
entry_username = tk.Entry(form_frame)
entry_username.grid(row=0, column=1, padx=5, pady=5)
# Password
label_password = tk.Label(form_frame, text="Password:")
label_password.grid(row=1, column=0, padx=5, pady=5, sticky="e")
entry_password = tk.Entry(form_frame, show="*")
entry_password.grid(row=1, column=1, padx=5, pady=5)
# Login Button
login_button = tk.Button(root, text="Login", command=login)
login_button.pack(pady=10)
# --- Start the Event Loop ---
root.mainloop()

Key improvements in this example:

  • messagebox: Imported to show pop-up dialogs.
  • command=login: The button's command is now linked to our login function. When clicked, the function will be executed.
  • .get(): This method retrieves the current text from an Entry widget.
  • sticky="e": An option for grid() that aligns the widget within its cell. "e" is for east (right), "w" for west (left), "n" for north (top), etc.
  • Frame: We used a Frame to group the labels and entries, which makes the layout cleaner and more organized.

Important Note on Python 3.3 vs. Modern Python (3.6+)

You specifically asked about Python 3.3. While the core Tkinter API is stable, there are a few things to be aware of:

  1. Import Statement: In Python 3, the module is import tkinter, not import Tkinter. This is a common source of error for those moving from Python 2.
  2. tkinter.ttk (Themed Tkinter): Python 3.3 includes the ttk module, which provides "themed" widgets that look more modern and are consistent across different operating systems (Windows, macOS, Linux). It's highly recommended to use ttk widgets whenever possible.
    • Example: from tkinter import ttk and then button = ttk.Button(...)
  3. Development Status: Python 3.3 reached its end-of-life in September 2025. This means it no longer receives security updates or bug fixes. For any new project, you should use a more recent, supported version of Python (e.g., 3.8, 3.9, 3.10, or newer). The principles and code shown here will work identically in those versions.

Resources for Learning

  • The Official Python Tkinter Documentation: The best place for reference on every widget and method.
  • TkinterBooks by Alan D. Moore: An excellent free online book that is very comprehensive and easy to follow.
  • Effbot's Tkinter Documentation: A classic, highly-regarded reference by Fredrik Lundh (a key figure in Tkinter's history). The site might look dated, but the content is timeless.
  • Stack Overflow: An invaluable resource for solving specific problems. Just search for "python tkinter [your problem]".
分享:
扫描分享到社交APP
上一篇
下一篇