📅  最后修改于: 2023-12-03 14:46:05.068000             🧑  作者: Mango
Python tkinter is a library that provides a Python interface to the Tk GUI toolkit. Tk is a standard GUI toolkit for Tcl, and provides a simple and powerful way to create graphical user interfaces.
To start using tkinter, you need to import the library and create a main window. Here’s some example code:
import tkinter as tk
root = tk.Tk()
root.mainloop()
This will create a blank window, which will remain open until you close it.
Widgets are the building blocks of tkinter user interfaces. They can be added to a window using the pack
, grid
, or place
methods. Here’s an example of a label widget:
label = tk.Label(root, text="Hello, world!")
label.pack()
This will create a label with the text “Hello, world!” and add it to the main window using the pack
method.
Interactivity is a key aspect of GUI programming, and tkinter provides a way to handle user events such as mouse clicks and key presses. Here’s an example of a button widget that responds to a click event:
def on_button_click():
label.config(text="Button clicked!")
button = tk.Button(root, text="Click me", command=on_button_click)
button.pack()
This will create a button with the text “Click me” that, when clicked, will change the label text to “Button clicked!”.
Python tkinter is a versatile and easy-to-use library for creating GUIs in Python. With its extensive documentation and active community, it’s a great choice for both beginners and experienced programmers.