Here's a basic example of how to use Python Tkinter
Here's a basic example of how to use Python Tkinter to create a simple GUI application with a label and a button:
Python
import tkinter as tk
# Create the main window
window = tk.Tk()
# Set the title of the window
window.title("Sample Tkinter App")
# Create a label widget
label = tk.Label(window, text="Hello, Tkinter!")
label.pack() # Pack the label widget into the window
# Define a function to handle button click
def click_me():
label.config(text="Button clicked!") # Change the label text
# Create a button widget
button = tk.Button(window, text="Click Me", command=click_me)
button.pack() # Pack the button widget into the window
# Run the main loop to keep the window open
window.mainloop()
Explanation:
- We import
tkinter
astk
for easier use. - We create the main application window using
tk.Tk()
. - We set the title of the window using the
title()
method. - We create a label widget using
tk.Label()
with some text. - We use the
pack()
method to arrange the label widget inside the window. There are other layout managers available in Tkinter likegrid
andplace
. - We define a function
click_me()
that changes the label text when the button is clicked. - We create a button widget using
tk.Button()
, specifying the text and the function to call (command
) when clicked. - We again use
pack()
to arrange the button widget. - Finally, we call
window.mainloop()
to run the main application loop and keep the window displayed until closed by the user.
This is a very basic example, but it demonstrates the core concepts of creating widgets, arranging them in the window, and handling user interactions with Tkinter. You can explore further to create more complex and interactive GUIs using various widgets and functionalities offered by Tkinter.
コメント
コメントを投稿