📜  Python Tkinter(1)

📅  最后修改于: 2023-12-03 15:04:09.451000             🧑  作者: Mango

Python Tkinter

Python Tkinter is a standard Python library for creating GUI (Graphical User Interface) applications. It provides a way to build desktop applications that run on Windows, Mac, and Linux.

Installing and Importing Tkinter

Tkinter is included with most Python installations, so you can simply import it:

import tkinter as tk
Creating a Tkinter Window

Creating a basic window with Tkinter only requires a few lines of code:

import tkinter as tk
 
root = tk.Tk()
root.mainloop()

This will create a window with a title bar and an empty space inside.

Tkinter Widgets

Tkinter provides a wide range of widgets that can be added to your GUI:

  • Labels
  • Buttons
  • Checkboxes
  • Radiobuttons
  • Entry fields
  • Textboxes
  • Menus
  • and more...

Here's an example of a window with several widgets:

import tkinter as tk
 
root = tk.Tk()
root.title("My GUI")
 
# Create a label
label = tk.Label(root, text="Hello, Tkinter!")
label.pack()
 
# Create a button
button = tk.Button(root, text="Click me!")
button.pack()
 
# Create a textbox
textbox = tk.Text(root)
textbox.pack()
 
root.mainloop()
Tkinter Layout Managers

Layout managers are used to arrange the widgets in a window. Tkinter provides several layout managers:

  • Pack - arranges widgets in horizontal or vertical boxes
  • Grid - arranges widgets in a grid
  • Place - explicitly sets the position of widgets

Here's an example of using the pack layout manager:

import tkinter as tk
 
root = tk.Tk()
root.title("Pack Example")
 
# Create labels and buttons
label1 = tk.Label(root, text="Label 1")
label2 = tk.Label(root, text="Label 2")
button1 = tk.Button(root, text="Button 1")
button2 = tk.Button(root, text="Button 2")
 
# Pack widgets vertically
label1.pack()
button1.pack()
label2.pack()
button2.pack()
 
root.mainloop()
Conclusion

Python Tkinter is a powerful library for creating GUI applications. With the wide range of widgets and layout managers available, you can create complex and rich user interfaces. Check the official documentation for more information and examples.