tkinter GUI programming (learning note-1)

Developing graphical user interface (GUI) applications is one of the important applications of Python. The standard library tkinter is used to realize the graphical user interface.
tkinter module is Python's de facto GUI library, which is included in Python's basic installation package.
The GUI program written with tkinter module is cross platform and can run in a variety of operating systems.

First tkinter GUI program
Component and container are two basic concepts of GUI programming.
● components refer to labels, buttons, list boxes and other objects, which need to be displayed in containers.
● container refers to the object that can place other components or containers.

#tkinter GUI program with labels and buttons
import tkinter      #Import tkinter module
win=tkinter.Tk()    #Create main window object
label1=tkinter.Label(win,text="Hello,Python")  #Create label object
btn1=tkinter.Button(win,text='click')                 #Create button object
label1.pack()   #Package the object so that it appears in its parent container
btn1.pack()
win.mainloop()   #Start event cycle

 

tkinter GUI programming steps
(1) import tkinter module. import tkinter or # from tkinter import*
(2) Create the main window object. If the main window object is not created, tkinter will use the default top-level window as the main window.
(3) Create component objects such as labels, buttons, and input text boxes.
(4) Package the component and display it in its parent container.
(5) Start the event cycle, start the GUI window, and wait for the response to the user's operation.

import tkinter 
from tkinter import*

Set properties for windows and components
The common methods for setting window properties are title(), geometry(), and config().
1. title() method and geometry() method
The title() method is used to set the title of the window, and the geometry() method is used to set the size of the window.
The parameter format in the geometry() method is "width x height".  

#Set window title and size
from tkinter import *     #Import tkinter module
win=Tk()    #Create main window object
label1=Label(win,text="Hello,Python")  #Create label object
btn1=Button(win,text='click')                 #Create button object
label1.pack()   #Package the object so that it appears in its parent container
btn1.pack()
win.title("Set window title and size")      # The title() method sets the window title
win.geometry("300x200")             # The geometry() method sets the window size
win.mainloop()   #Start event cycle

2. config() method
The config() method is used to set the component text, alignment, foreground color, background color, font and other properties.

#Use the config() method to set component properties
from tkinter import *     #Import tkinter module
win=Tk()           #Create main window object

label=Label()    #Create label object
label.config(text="Hello Python")    #Set text properties
label.config(fg="white",bg="blue")  #Set foreground and background properties
label.pack()      #Package the object so that it appears in its parent container

btn1=Button()                 #Create button object
btn1["text"]="click"
btn1.pack()

win.title("Set component properties")      # The title() method sets the window title
win.geometry("300x200")        # The geometry() method sets the window size
win.mainloop()   #Start event cycle

Layout management of tkinter GUI
● the layout of components in the container is very cumbersome. It is necessary to adjust the size of the components themselves and design the relative position with other components.
● the method of implementing component layout is called layout manager or geometry manager.
● tkinter uses three methods to realize layout: pack(), grid(), place(),.
● as the container component of the middle layer, Frame can manage components in groups to realize complex layout.

Layout using the pack() method
The pack() method lays out the components in blocks.
The pack() method displays components in the default location, which is the simplest and most direct use.
Parameters of pack() method:
side indicates the position of the component in the container;
· expand indicates that the component can be stretched;
· fill takes the value of X, y or BOTH to fill the space in the X or Y direction;
· anchor indicates the position of the component in the window.  

#Use the side parameter of the pack() method to set the layout of the component
from tkinter import *     #Import tkinter module
win=Tk()           #Create main window object

label1=Label(win,text="Top label",fg="white",bg="blue")    #Create label object
label2=Label(win,text="Left label",fg="white",bg="blue")    
label3=Label(win,text="Bottom label",fg="white",bg="blue")   
label4=Label(win,text="Right label",fg="white",bg="blue")  

label1.pack(side=TOP)      #Package the object so that it appears in its parent container
label2.pack(side=LEFT) 
label3.pack(side=BOTTOM) 
label4.pack(side=RIGHT) 

win.title("pack()method")             # The title() method sets the window title
win.geometry("200x150")             # The geometry() method sets the window size
win.mainloop()   #Start event cycle

 

#Use the anchor parameter of the pack() method to set the layout of the component
from tkinter import *     #Import tkinter module
win=Tk()           #Create main window object

label1=Label(win,text="Label title",fg="white",bg="blue")    #Create label object
label1.pack(anchor=NW,padx=5)   

label2=Label(win)    
label2.config(text="Label content",fg="white",bg="grey")   
label2.pack(expand=YES,fill=BOTH,padx=5)

btn=Button()
btn["text"]="click"
btn.pack()              #packed object 

win.title("anchor Parameter setting")         # The title() method sets the window title
win.geometry("300x200")             # The geometry() method sets the window size
win.mainloop()   #Start event cycle

Layout using grid() method
The layout using grid() method is called grid layout. It divides the container into several rows and columns in the form of two-dimensional table, and the position of components is determined by the position of rows and columns.
In the same container, only one of the pack() method or grid() method can be used.
Parameters of grid() method:
· row and column, the position of the row and column where the component is located
· rowspan and columnspan, the number of rows and columns spanned by the component from its location
· sticky, alignment of component location

#Use the grid() method to set the layout of components
from tkinter import *     #Import tkinter module
win=Tk()           #Create main window object

label1=Label(win,text="Please select the following actions",fg="green")    #Create label object
label1.grid(row=0,column=0,columnspan=4)   

btn1=Button(text="copy")
btn2=Button(text="cut")
btn3=Button(text="paste")
btn4=Button(text="delete")
btn1.grid(row=2,column=0,padx=2)   
btn2.grid(row=2,column=1,padx=2)  
btn3.grid(row=2,column=2,padx=2)  
btn4.grid(row=2,column=3,padx=2)  

win.title("grid()Method settings")           # The title() method sets the window title
win.geometry("200x150")             # The geometry() method sets the window size
win.mainloop()   #Start event cycle

Layout using the place() method
The location of the components in the container () is more precisely controlled than the layout of the pack() and the grid().
If the container is resized, the layout may not adapt.
Parameters of the place() method
· x and y, specify the position of the component with absolute coordinates
· height and width, specify the height and width of the component
· relx and rely, which specify the position of components in proportion to the height and width of the container
· relheight and relwidth, which specify the height and width of the component in proportion to the height and width of the container

#Use the place() method to set the layout of components
from tkinter import *     #Import tkinter module
win=Tk()           #Create main window object

label1=Label(win,text="place()Method test",fg="green")    #Create label object
label1.place(x=140,y=50,anchor=N)

btn1=Button(text="place()Button")
btn1.place(x=140,y=80,anchor=N)
btn2=Button(text="grid()Button")
btn2.grid(row=2,column=1)  

win.title("place()Method settings")           # The title() method sets the window title
win.geometry("200x150")             # The geometry() method sets the window size
win.mainloop()   #Start event cycle

Complex layout using frames
A frame is a container component that is often used to group components
This allows for complex layouts.
· bd# specify border width
· relief specifies the border style with values of flat (default), raised, sunken, ridge, groove and solid
· width and height set the width or height. If omitted, the container usually adjusts the Frame size according to the size of the content component

#Complex layout using Frame
from tkinter import *     #Import tkinter module
win=Tk()           #Create main window object
frma=Frame()   #Frame frma
frmb=Frame()   #Frame frmb
frma.pack()   
frmb.pack()

#Add two labels and two input boxes
lblUname=Label(frma,text="UserName",width=10,fg="black")
etyUname=Entry(frma,width=20)
lblUname.grid(row=1,column=1)
etyUname.grid(row=1,column=2)
lblPwd=Label(frma,text="PassWord",width=10,fg="black")
etyPwd=Entry(frma,width=20)
lblPwd.grid(row=2,column=1)
etyPwd.grid(row=2,column=2)
#Add two buttons to the container
btnRest=Button(frmb,text="ReSet",width=10)
btnSubmit=Button(frmb,text="Submit",width=10)
btnRest.grid(row=1,column=1)
btnSubmit.grid(row=1,column=2)

win.title("Frame Realize complex layout")           # The title() method sets the window title
win.geometry("300x150")             # The geometry() method sets the window size
win.mainloop()   #Start event cycle

#Test label properties
from tkinter import *     #Import tkinter module
str="Attribute test of tag"
mylabel=Label(text=str)                     
mylabel.config(justify=CENTER)         #Set text center alignment
mylabel.config(width=20,height=4)    #Sets the width and height of the label in characters
mylabel.config(bd=2,relief=SOLID)     #Sets the width of the border
mylabel.config(wraplength=160)        #Set the text rewind width to 160 pixels
mylabel.config(anchor=W)                  #The setting content is on the left inside the label
mylabel.config(font=('Song style',18))         #Set font
mylabel.pack(side=TOP)                      #Set the label at the top of the window
mainloop()   #Start event cycle

 

 

#The Button component calculates the cumulative value of 1 ~ 100
from tkinter import *     #Import tkinter module
win=Tk()
win.title("Button Test")
win.geometry("300x200")
labell=Label(win,text="The calculation results are displayed here")
labell.config(font=("Song style",12))
labell.pack()

def computing():
    sum=0
    for i in range(100+1):
        sum+=i
    result="The cumulative result is:"+str(sum)
    labell.config(text=result)

str1='Calculate 1-100 cumulative value'
mybutton=Button(win,text=str1)
mybutton.config(justify=CENTER)          #Center button text
mybutton.config(width=20,height=3)       #Sets the width and height of the button
mybutton.config(bd=3,relief=RAISED)      #Set the width and style of the border
mybutton.config(anchor=CENTER)           #The setting content is centered inside the button
mybutton.config(font=("official script",12,"underline"))

mybutton.config(command=computing)              #The command property specifies the response function
mybutton.config(activebackground="yellow")      #Click background color
mybutton.config(activeforeground="red")         #Click foreground color
mybutton.pack()
win.mainloop()   #Start event cycle

 

# The Entry component inputs data and calculates the cumulative sum
from tkinter import *     #Import tkinter module

def computing():
    sum=0
    n=int(number.get())
    for i in range(n+1):
        sum+=i
    result="The cumulative result is:"+str(sum)
    label3.config(text=result)

win=Tk()
win.title("Entry Test")
win.geometry("300x200")

label1=Label(win,text="Please enter calculation data:")
label1.config(width=16,height=3)
label1.config(font=("Song style",12))
label1.grid(row=0,column=0)
number=StringVar() 
entry1=Entry(win,textvariable=number,width=16)
entry1.grid(row=0,column=1)

label2=Label(win,text="Click OK:")
label2.config(width=14,height=3)
label2.config(font=("Song style",12))
label2.grid(row=1,column=0)

mybutton=Button(win,text='calculation')
mybutton.config(justify=CENTER)          #Center button text
mybutton.config(width=14,height=2)       #Sets the width and height of the button
mybutton.config(bd=3,relief=RAISED)      #Set the width and style of the border
mybutton.config(anchor=CENTER)           #The setting content is centered inside the button
mybutton.config(font=("official script",12))
mybutton.config(command=computing)       #The command property specifies the response function
mybutton.grid(row=1,column=1)

label3=Label(win,text="Display results")
label3.config(width=16,height=3)
label3.config(font=("Song style",12))
label3.place(x=50,y=130)

win.mainloop()   #Start event cycle

 

 

myvar=BooleanVar()
myvar=StringVar()
myvar=IntVar()
myvar=DoubleVar()
# Listbox operation listbox component
from tkinter import *     #Import tkinter module

win=Tk()
listbox=Listbox(win)
#Initialize list box
items=["HTML5","CSS3","JavaScript","Jquery"]
for item in items:
    listbox.insert(END,item)
listbox.pack(side=LEFT,expand=1,fill=Y)

def additem():         #Add options to the list
    str=entry1.get()    #Get string
    if not str=="":
        index=listbox.curselection()
        if len(index)>0:
            listbox.insert(index[0],str)  #There is a selected item. Add an item before the selected item
        else:
            listbox.insert(END,str)        #No selected items added to last
            
def removeitem():   #Remove option from list
    index=listbox.curselection()
    if len(index)>0:
        listbox.delete(index[0],index[-1])  #Delete selected items 
    else:
        listbox.delete(index[0])                 #Delete the selected item
            
entry1=Entry(width=20)
entry1.pack(anchor=NW)
bt1=Button(text="add to",command=additem)
bt1.pack(anchor=NW)
bt2=Button(text="delete",command=removeitem)
bt2.pack(anchor=NW)

win.mainloop()   #Start event cycle

 

# Radiobutton component radio button group operation example
from tkinter import *     #Import tkinter module

win=Tk()
label1=Label(win,text="Please vote for your favorite sport")
label1.grid(row=1,column=1,columnspan=2)

s_items=IntVar()
s_items.set(2)

frame1=Frame(bd=2,relief=RIDGE)  #Frame 1
frame1.grid(row=2,column=1)

frame2=Frame(bd=0,relief=RIDGE)  #Frame 2
frame2.grid(row=2,column=2)

radio1=Radiobutton(frame1,text="Football",variable=s_items,value=1,width=8)
radio1.grid(row=1,column=1)
radio2=Radiobutton(frame1,text="Volleyball",variable=s_items,value=2,width=8)
radio2.grid(row=2,column=1)
radio3=Radiobutton(frame1,text="Basketball",variable=s_items,value=3,width=8)
radio3.grid(row=3,column=1)

num1=IntVar()
entry1=Entry(frame2,textvariable=num1,width=10,state='readonly')
entry1.grid(row=1,column=1,pady=4)
num2=IntVar()
entry2=Entry(frame2,textvariable=num2,width=10,state='readonly')
entry2.grid(row=2,column=1,pady=4)
num3=IntVar()
entry3=Entry(frame2,textvariable=num3,width=10,state='readonly')
entry3.grid(row=3,column=1,pady=4)

def voting():
    global num1,num2,num3
    temp=s_items.get()
    if temp==2:
        num2.set(num2.get()+1)
    elif temp==1:
        num1.set(num1.get()+1)
    else:
        num3.set(num3.get()+1)
        
bt1=Button(win,text="Please vote",command=voting)
bt1.grid(row=3,column=1,columnspan=2,pady=5)

win.geometry("300x200")
win.mainloop()   #Start event cycle

 

Tags: Python Tornado

Posted by toshog on Fri, 15 Apr 2022 11:26:02 +0930