Python- GUI GUI Level 1 application creation
TKINTER/PYQT
CDSID: lvishwan
1
LEVEL -4
Contents : TKINTER
Threading
py to EXE
Introduction
Graphical User Interface is the form of user interface allow the user interact with computer software's through graphical icons and visual indicators. It is consider to be a more user friendly then text based command line interface.
It is easy to operate also it works without prior knowledge. It clearly project the visual feedback about the effect of each actions how to carryout.
Python offers multiple options to develop GUI, but tkinter is the most commonly used method. Python with tkinter outputs the fastest and easiest way to create the GUI applications.
Note:- Name of the module in Python 2.x version is ‘Tkinter’ and in Python 3.x version is ‘tkinter’.
Python 3.x Python 2.x
Basic code to create main window
Name of window
Add all the widgets between these area
Makes the window not closed and wait for
event to occur
Sample Script: Output:
Tkinter widgets
Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI application. These controls are commonly called widgets.
tkinter also offers access to the geometric configuration of the widgets which can organize the widgets in the parent windows. There are mainly three geometry manager classes class
Label
This widget act like a display box wherever we can place the text or image in the parent window.
Example: Output:
Button
By using this widget we can attach a function or a method to a button, which is automatically run when we click the button.
Example: Output:
Button
#2 Example:
To add a button in your application, this widget is used.
The general syntax is:
w=Button(master, option=value)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Radio Button
This widget implements a multiple-choice button, which is a way to offer many possible selections to the user, and let user choose only one of them. It must be associated to the same variable.
Example: Output:
Check box
Check box is the small interactive box which is easy way to enable or disable a setting in a software.
Example: Output:
Entry
Entry widget used to accept the single line text from the user for multiple line go with text widget.
Example: Output:
Combobox
This widget used to create list of multiple choice and it is the class of ttk module.
Example: Output:
List box
Listbox widget is used to display a list of items from which a user can select a number of items.
Example: Output:
list box
This widget provides a slide controller that is used to implement vertical scrolled widgets, such as Listbox, Text, and Canvas. Note that you can also create horizontal scrollbars on Entry widgets.
Example: Output Video:
Spin box
Spinbox widget is a variant of the standard Tkinter Entry widget, which can be used to select from a fixed number of values.
Example: Output:
Scale
Scale widget provides a graphical slider object that allows you to select values from a specific scale.
Example: Output Video:
Page configuration
Frame
Frame widget is very important for the process of grouping and organizing other widgets. It works like a container, which is responsible for arranging the position of other widgets.
Example: Output Video:
LabelFrame
This widget has the same features of a frame plus the ability to display a label.
Example: Output:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title("Tab Widget")
tabControl = ttk.Notebook(root)
tab1 = ttk.Frame(tabControl)
tab2 = ttk.Frame(tabControl)
tabControl.add(tab1, text ='Tab 1')
tabControl.add(tab2, text ='Tab 2')
tabControl.pack(expand = 1, fill ="both")
ttk.Label(tab1,text ="Welcome to GeeksForGeeks").grid(column = 0,row = 0,padx = 30,pady = 30)
ttk.Label(tab2,text ="Lets dive into the world of computers").grid(column = 0,row = 0,padx = 30,pady = 30)
root.mainloop()
Note book /TAB
Stacked Widget
from tkinter import *
def raise_frame():
global current
pages=(f1,f2,f3,f4)
i=pages.index(current)
if i==len(pages)-1:i=-1
current=pages[i+1]
current.tkraise()
w = Tk()
f1 = Frame(w);f1.grid(row=0, column=0)
f2 = Frame(w);f2.grid(row=0, column=0)
f3 = Frame(w);f3.grid(row=0, column=0)
f4 = Frame(w);f4.grid(row=0, column=0)
Label(f1, text='FRAME 1').pack()
Label(f2, text='FRAME 2').pack()
Label(f3, text='FRAME 3').pack()
Label(f4, text='FRAME 4').pack()
current=f4
Button(w,text='next',command=raise_frame).grid(row=1,column=0)
w.mainloop()
menu bar
from tkinter import *
root = Tk()
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label='File', menu=filemenu)
filemenu.add_command(label='New')
filemenu.add_command(label='Open...')
filemenu.add_separator()
filemenu.add_command(label='Exit', command=root.quit)
helpmenu = Menu(menu)
menu.add_cascade(label='Help', menu=helpmenu)
helpmenu.add_command(label='About')
mainloop()
import tkinter
from tkinter import *
def rename():print('rename selected')
root = Tk()
L = Label(root, text ="Right-click to display menu",
width = 40, height = 20)
L.pack()
m = Menu(root, tearoff = 0)
m.add_command(label ="Cut")
m.add_command(label ="Copy")
m.add_command(label ="Paste")
m.add_command(label ="Reload")
m.add_separator()
m.add_command(label ="Rename",command=rename)
def do_popup(event):
try:m.tk_popup(event.x_root, event.y_root)
finally:m.grab_release()
L.bind("<Button-3>", do_popup)
mainloop()
Right click menu
CDSID: lvishwan
28
CDSID: lvishwan
29
tkinter.ttk is a module that is used to style the tkinter widgets. Just like CSS is used to style an HTML element, we use tkinter.ttk to style tkinter widgets.
Here are the major differences between tkinter widget and tkinter.ttk −
Themed tk widgets
Canvas
Tkinter canvas
A tkinter canvas can be used to draw in a window. Use this widget to draw graphs or plots. You can even use it to create graphical editors.
You can draw several widgets in the canvas: arc bitmap, images, lines, rectangles, text, pieslices, ovals, polygons, ovals, polygons, and rectangles. Rectangles can be both outline and interior.
import tkinter
# init tk
root = tkinter.Tk()
# create canvas
myCanvas = tkinter.Canvas(root, bg="white", height=300, width=300)
# draw arcs
coord = 10, 10, 300, 300
arc = myCanvas.create_arc(coord, start=0, extent=150, fill="red")
arv2 = myCanvas.create_arc(coord, start=150, extent=215, fill="green")
# add to window and show
myCanvas.pack()
root.mainloop()
from tkinter import *
from tkinter.ttk import *
class GFG:
def __init__(self, master = None):
self.master = master
self.create()
def create(self):
self.canvas = Canvas(self.master)
self.canvas.create_line(15, 25, 200, 25)
self.canvas.create_line(300, 35, 300, 200, dash = (5, 2))
self.canvas.create_line(55, 85, 155, 85, 105, 180, 55, 85)
self.canvas.pack(fill = BOTH, expand = True)
if __name__ == "__main__":
master = Tk()
geeks = GFG(master)
master.title("Lines")
master.geometry("400x250 + 300 + 300")
master.mainloop()
from tkinter import *
from tkinter.colorchooser import askcolor
class Paint(object):
DEFAULT_PEN_SIZE = 5.0
DEFAULT_COLOR = 'black'
def __init__(self):
self.root = Tk()
self.pen_button = Button(self.root, text='pen', command=self.use_pen)
self.pen_button.grid(row=0, column=0)
self.brush_button = Button(self.root, text='brush', command=self.use_brush)
self.brush_button.grid(row=0, column=1)
self.color_button = Button(self.root, text='color', command=self.choose_color)
self.color_button.grid(row=0, column=2)
self.eraser_button = Button(self.root, text='eraser', command=self.use_eraser)
self.eraser_button.grid(row=0, column=3)
self.choose_size_button = Scale(self.root, from_=1, to=10, orient=HORIZONTAL)
self.choose_size_button.grid(row=0, column=4)
self.c = Canvas(self.root, bg='white', width=600, height=600)
self.c.grid(row=1, columnspan=5)
self.setup()
self.root.mainloop()
Draw by mouse
def setup(self):
self.old_x = None
self.old_y = None
self.line_width = self.choose_size_button.get()
self.color = self.DEFAULT_COLOR
self.eraser_on = False
self.active_button = self.pen_button
self.c.bind('<B1-Motion>', self.paint)
self.c.bind('<ButtonRelease-1>', self.reset)
def use_pen(self):
self.activate_button(self.pen_button)
def use_brush(self):
self.activate_button(self.brush_button)
def choose_color(self):
self.eraser_on = False
self.color = askcolor(color=self.color)[1]
def use_eraser(self):
self.activate_button(self.eraser_button, eraser_mode=True)
def activate_button(self, some_button, eraser_mode=False):
self.active_button.config(relief=RAISED)
some_button.config(relief=SUNKEN)
self.active_button = some_button
self.eraser_on = eraser_mode
def paint(self, event):
self.line_width = self.choose_size_button.get()
paint_color = 'white' if self.eraser_on else self.color
if self.old_x and self.old_y:
self.c.create_line(self.old_x, self.old_y, event.x, event.y,
width=self.line_width, fill=paint_color,
capstyle=ROUND, smooth=TRUE, splinesteps=36)
self.old_x = event.x
self.old_y = event.y
def reset(self, event):
self.old_x, self.old_y = None, None
if __name__ == '__main__':
Paint()
Matplotlib
import matplotlib.pyplot as plt
xpoints = [1,2,3,4]
ypoints = [5,6,8,3]
plt.plot(xpoints, ypoints)
plt.show()
# marker
plt.plot(xpoints, ypoints,'o')
#default x value
ypoints = [5,6,8,3]
plt.plot( ypoints,'o')
plt.show()
#marker,line-type, color
plt.plot(ypoints, 'o:r')
Line props | |
linewidth = '20.5' | |
ls=’:’ | |
color = 'r' | |
Marker props | |
| |
| |
Label
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")
plt.title("Sports Watch Data")
plt.title("Sports Watch Data", fontdict = {'family':'serif','color':'darkred','size':15})
plt.title("Sports Watch Data", loc = 'left'))
plt.grid()
plt.grid(axis = 'x')
plt.grid(color = 'green', linestyle = '--', linewidth = 0.5)
Py to EXE
pip install auto-py-to-exe
import auto_py_to_exe.__main__
auto_py_to_exe.__main__.run()
PyQt5
No. | Basis | PyQt | Tkinter |
1. | License | PyQt is available under Riverbank Commercial License and GPL v3 (General Public License v 3.0) and if you do not wish to release your application under a GPL-compatible license, you must apply for a commercial license. | Tkinter is open source and free for any commercial use. |
2. | Ease of Understanding | It requires a lot of time for understanding all the details of PyQt. | Tkinter is easy to understand and master due to a small library. |
3. | Design | PyQt has a modern look and a good UI. | Tk had an older design and it looks outdated. |
4. | Widgets | thenPyQt comes with many powerful and advanced widgets. | TkInter does not come with advanced widgets. |
5. | UI Builder | PyQt have a Qt Designer tool which we can use to build GUIs than get python code of that GUI using Qt Designer. | It has no similar tool as Qt Designer for Tkinter. |
6. | Installation | PyQt is not included by default with Python installations. | It is included in the standard Python library so no need to install it separately. |
Difference between PyQt and Tkinter
Kivy
import kivy
kivy.require('1.0.6')
from glob import glob
from os.path import join, dirname
from kivy.app import App
from kivy.logger import Logger
from kivy.uix.scatter import Scatter
from kivy.properties import StringProperty
import os
class Picture(Scatter):
source = StringProperty(None)
class PicturesApp(App):
def build(self):
# the root is created in pictures.kv
root = self.root
curdir='/storage/emulated/0/Pictures/del/Screenshots/'
for filename in [curdir+file for file in os.listdir(curdir)]:
try:
# load the image
picture = Picture(source=filename, rotation=0)
# add to the main field
root.add_widget(picture)
except Exception as e:
Logger.exception('Pictures: Unable to load <%s>' % filename)
def on_pause(self):
return True
if __name__ == '__main__':
PicturesApp().run()