📅  最后修改于: 2023-12-03 15:34:00.940000             🧑  作者: Mango
Python GUI – tkinter is a standard Python library used for creating graphical user interfaces (GUIs). It provides a great way to build interfaces like windows, frames, and buttons. The library was named after the popular toolkits called Tk–Tkinter. The tkinter
module comes as a part of Python standard libraries, so there is no need to install it separately.
Tk is one of the most common GUI toolkits for Python. tkinter is the Python interface to Tk, and it comes in a standard Python distribution making it available for all platforms.
With tkinter, we can easily create windows, frames, buttons, text, check-boxes, radio buttons, images, and many more controls.
There is no need to install tkinter
separately, as it comes as standard with Python installations.
We can create a basic GUI using tkinter
with a few lines of code:
import tkinter as tk
root = tk.Tk()
root.title("GUI Sample")
root.mainloop()
The code creates a new buttonless window with the title "GUI Sample". The root
object represents the main window of the application. The mainloop()
method starts the main event loop and waits for user input.
We can add controls like buttons, labels, and text boxes to the window using the various methods of tkinter
.
Following are some of the methods used in tkinter
widgets:
pack()
- organizes the widget in the parent containerplace()
- places the widget at a specific position in the parent containergrid()
- places the widget in a grid layoutBelow is a simple GUI application that includes a button and a label:
import tkinter as tk
def click_me():
label.config(text="Hello, Python GUI!")
root = tk.Tk()
root.title("Python GUI")
label = tk.Label(root, text="Click the button to see a message!")
label.pack()
button = tk.Button(root, text="Click Me!", command=click_me)
button.pack()
root.mainloop()
The Label
widget shows a text message, and the Button
widget has an associated callback function, click_me
, which changes the message in the label widget.
Tkinter
is a great module to create graphical user interfaces. It works on all platforms and is easy to learn. We can create custom widgets, bind events, and create complex layouts using this module.