Problem Statement: Write Python code that creates a simple graphical user interface (GUI) application.
Program Implementation and Explanation:
import tkinter as tk
from tkinter import messagebox
def display_greeting():
"""Displays a greeting message."""
name = name_entry.get()
if name.strip():
messagebox.showinfo("Greeting", f"Hello, {name}!")
else:
messagebox.showwarning("Input Error", "Please enter your name.")
# Create the main window
root = tk.Tk()
root.title("Greeting App")
root.geometry("300x200") # Set window size
# Create and place widgets
greeting_label = tk.Label(root, text="Enter your name:", font=("Arial", 12))
greeting_label.pack(pady=10)
name_entry = tk.Entry(root, width=30, font=("Arial", 12))
name_entry.pack(pady=5)
greet_button = tk.Button(root, text="Greet Me!", font=("Arial", 12), command=display_greeting)
greet_button.pack(pady=10)
quit_button = tk.Button(root, text="Quit", font=("Arial", 12), command=root.quit)
quit_button.pack(pady=10)
# Start the application
root.mainloop()
------------------------------------------
Explanation:
1. tkinter(Library): It is the python standard Library.
2. root (Main Window): It represents the main GUI window which appears on the screen when we run the code.
geometry is the method to set the window size.
title is the method which sets the title of window.
3. Widgets: It is nothing but graphical component through which user can interact with the application.
Label: On main window if you want to display the text then we have to use Label widget.
Entry: If you want to supply input to the application the use this widget. accepting input from user.
Button: if you want button to perform some operation then use this widget.
4. Event Handling: When we click on button some event occurs immediately. that event is going to handle by following event handler.
command: through this parameter we bind the function that we want must happen after button click.
messagebox: It is the module used to display popup message.
5. root.mainloop(): This is the event loop; it runs continuously until and unless user does not close it.
No comments:
Post a Comment