Python GUI with Simple Examples
1. GUI (Graphical User Interface)
GUI allows users to interact with the program using **buttons, windows, text boxes**, etc.
Python provides GUI using **Tkinter**.
---
2. Tkinter Basics
To use Tkinter:
```python
from tkinter import *
root = Tk()
[Link]()
```
* `Tk()` → creates window
* `mainloop()` → keeps window open
---
3. Label Widget
Used to display text.
```python
from tkinter import *
root = Tk()
Label(root, text="Hello").pack()
[Link]()
```
---
4. Button Widget
Used to perform an action.
```python
from tkinter import *
def show():
print("Clicked!")
root = Tk()
Button(root, text="Click Me", command=show).pack()
[Link]()
```
---
5. Entry Widget
Single-line input box.
```python
from tkinter import *
root = Tk()
e = Entry(root)
[Link]()
[Link]()
```
---
6. Geometry Managers
Used to position widgets.
* `pack()` – simple layout
* `grid()` – row/column
* `place()` – fixed position
Example:
```python
Label(root, text="Name").grid(row=0, column=0)
Entry(root).grid(row=0, column=1)
```
---
7. Checkbutton & Radiobutton
### Checkbutton:
```python
Checkbutton(root, text="I Agree").pack()
```
### Radiobutton:
```python
Radiobutton(root, text="Male", value=1).pack()
Radiobutton(root, text="Female", value=2).pack()
```
---
8. Messagebox
Used to show alerts.
```python
from tkinter import *
from tkinter import messagebox
root = Tk()
[Link]("Info", "Hello!")
[Link]()
```
---
9. File Dialog
Used to open files.
```python
from tkinter import *
from tkinter import filedialog
root = Tk()
file = [Link]()
print(file)
```
---
10. Canvas Widget
Used for drawing shapes.
```python
from tkinter import *
root = Tk()
c = Canvas(root, width=200, height=150)
[Link]()
c.create_rectangle(50, 50, 150, 100)
[Link]()
```
---
11. Menu Bar
```python
from tkinter import *
root = Tk()
menu = Menu(root)
[Link](menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="Exit", command=[Link])
[Link]()
```
---
12. Simple Tkinter Mini App (Add Two Numbers)
```python
from tkinter import *
def add():
[Link](text=str(int([Link]()) + int([Link]())))
root = Tk()
e1 = Entry(root); [Link]()
e2 = Entry(root); [Link]()
Button(root, text="Add", command=add).pack()
result = Label(root, text="")
[Link]()
[Link]()
```
---