Starting GUI in Python

TKinter is the most widely used GUI library used in Python.In this post we shall cover the basics.

To start let us create the simplest of forms.

 

import tkinter as tk
root = tk.Tk()
root.title(string="My First Python Window")
root.mainloop()

Placing controls. To place a control in the window we create the control and pack it. Packing will place the control in the latest position on the window. We will study some sophisticated placement techniques later.

Placing a label

import tkinter as tk
root = tk.Tk()
root.title(string="My First Python Window")
lbl = tk.Label(root, text="My First Label")
lbl.pack()
root.mainloop()

Let us add some more controls now.

A button with text and a button with an image

import tkinter as tk
root = tk.Tk()
root.title(string="My First Python Window")
photo= tk.PhotoImage(file="e:/python.png")
print(photo)
lbl = tk.Label(root, text="My First Label")
button = tk.Button(root, text='My First Button')
photobutton = tk.Button(root,text="Photo",image=photo)
photobutton.image=photo
photobutton.pack()
button.pack()
lbl.pack()
root.mainloop()

Showing Message Boxes

from tkinter import messagebox

messagebox.showerror("Error Title", "This is the error message")
messagebox.showwarning("Warning Title","Some info about the warning")
messagebox.showinfo("Title about the info","Info message")
quit()

This will show three message boxes one after the other as you close them. Then a main window will come. The quit() in the end will quit the console.

Use a Textbox, Checkbox and RadioButtons

import tkinter as tk

root = tk.Tk()
languages=tk.StringVar()
root.title(string="User Inputs")
chk = tk.Checkbutton(root, text="Please check me")
ent = tk.Entry(root)
rd1 = tk.Radiobutton(root, text="Python", variable=languages,value="Python")
rd2 = tk.Radiobutton(root, text="Java", variable=languages,value="Java")
rd1.pack()
rd2.pack()
ent.pack()
chk.pack()
languages.set("Python")
root.mainloop()

Sliders using Scale

import tkinter as tk

root = tk.Tk()
root.title(string="Sliders")
horizontalscale = tk.Scale(root, from_=-10, to=40, orient=tk.HORIZONTAL)
horizontalscale.set(-10)
verticalscale = tk.Scale(root, from_=-10, to=40, orient=tk.VERTICAL)
verticalscale.set(-10)
verticalscale.pack()
horizontalscale.pack()
root.mainloop()

Listboxes

import tkinter as tk

root = tk.Tk()
root.title(string="Listboxes")
listbox = tk.Listbox(root)
listbox.pack()
listbox.insert(tk.END, "Nai Basti")
listbox.insert(tk.END, "Sarang Talab")
listbox.insert(tk.END, "Pahadia")
listbox.insert(tk.END, "Pandeypur")
root.mainloop()

 

 

dfsdfsdf

1 thought on “Starting GUI in Python”

Leave a Reply