Review of basic knowledge of python3 -- the ultimate choice for TKinter GUI

TKIinter – the ultimate choice for GUI

Python supports a variety of third-party libraries with graphical interfaces, including Tk, wxWidgets, QT, and GTK. Tkinter, our own library in Python, supports Tk. As the default GUI library, it can be used directly.

NOTE: the built-in Tkinter can meet the requirements of basic GUI programs. If it is a very complex GUI program, it is recommended to write it in the language and library originally supported by the operating system.

TK +interface = Tkinter

The Python code we write will call the built-in Tkinter, which encapsulates the interface to access Tk;

Tk is a graphic library that supports multiple operating systems and is developed using Tcl language;

Tk will call the local GUI interface provided by the operating system to complete the final GUI.

Therefore, our code only needs to call the interface provided by Tkinter.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

''' TKinter example Packaging usage of'''
# Define a frame with a button and a command to execute the action of clicking button
import tkinter as tk

class APP:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title('Tkinter example') # Set window title
        self.root.geometry('300x100+630+80') # Set the length and width of the main window and the position of the window on the screen: length x width +x+y
        self.frame = tk.Frame(self.root)
        self.frame.pack(side=tk.LEFT, padx=20, pady=30) # side is used to set the frame position and xy axis spacing
        self.interface()      

    def click(self):
        print("Hello World!!")
       
    def interface(self):
        self.button = tk.Button(self.frame, text="Hello!!", fg="red", bg="yellow", command=self.click)
        self.button.pack()


if __name__ == "__main__":
    app = APP()
    app.root.mainloop() # The window will disappear after the main program runs, so you can always see the window with a loop

Label

Label(master=None, **options)(class)

master - parent component

*Options - component options. The following table lists the specific meaning and usage of each option in detail

Display text or image, single font text (can span lines), individual characters underlined

If you want to display data that users can operate on, it may be more appropriate to use the Canvas component.

	EG:
# -*- coding: utf-8 -*-
	''' the Label and Button of tkinter  '''
	from tkinter import *
	
	root = Tk()
	frame1 = Frame(root)
	frame2 = Frame(root)
	photo = PhotoImage(file='minion.gif')
	
	def callback(): #Change text when button is clicked
	    text.set('NO WAY! You are just 3-month old!')
	
	text = StringVar()
	text.set('You are too young to play basketball!')
	
	theLabel = Label(frame1, textvariable=text, font="Kaiti, 22", justify='left')
	theLabel.pack(side='left', padx=10, pady=10)
	
	imageLabel = Label(frame1, image=photo)
	imageLabel.pack(side='right', padx=10, pady=10)
	
	
	button = Button(frame2, text='I can play!', font='kaiti, 22' ,command=callback)
	button.pack()
	
	frame1.pack(side='top')
	frame2.pack(pady=20)
	mainloop()
	
'''
	# show the text in front of image.
	
	textLabel = Label(root, text = 'Mr.Anzai, I want to play basketball!',
	                  image=photo,
	                  compound='center',
	                  justify='center',
	                  font='Lucida, 20')
	textLabel.pack()
'''

Button

*Button(master=None, **options) (class)

The features are similar to those of label, but a given function or method can be executed after being pressed. Button components are often used in toolbars, application windows, and dialog boxes to indicate acceptance or rejection.

checkbutton and Radiobutton components are more suitable for data input buttons.

state=DISABLED - indicates that the button is unavailable

Buttons vary by pixel:

f = Frame(master, height=64, width=64)
f.pack_propagate(0)
f.pack()

b = Button(f, text="determine", command=callback)
b.pack(fill=BOTH, expand=1)

b.config(relief=SUNKEN/RAISED) – the button remains pressed

compound=CENTER makes the text above the picture (overlapping display). Through LEFT, RIGHT, TOP and BOTTOM, you can set the text to be displayed next to the image

*method*:

flash()

-- Refresh Button Component, which will redraw Button Component several times (in ACTIVE and NORMAL Switching between states).

invoke()

-- call Button in command Option and returns the return value of the function.

-- If Button Status of is DISABLED(Not available) or not specified command Option, the method is invalid.

Checkbutton

Checkbutton(master=None, **options) (class)

master - parent component

*Options - component options. The following table lists the specific meaning and usage of each option in detail:

The default tab key is used to switch between buttons

To use Checkbutton, you must create a Tkinter variable to store the status of the button: (1 checked, 0 unchecked)

var = IntVar()
c = Checkbutton(master, text="I am Shuaiguo", variable=var)
c.pack()

indicator=FALSE - indicates that the selection box is not displayed

method:

deselect()

– uncheck the Checkbutton component, that is, set variable to offvalue.

flash()

– refresh the Checkbutton component, which redraws the Checkbutton component several times (switching between ACTIVE and NORMAL states).

invoke()

– call the function or method specified by the command option in the Checkbutton and return the return value of the function.

– if the status of the Checkbutton is DISABLED or the command option is not specified, the method is invalid.

select()

– set the Checkbutton component to the selected state, that is, set variable to onvalue.

toggle()

– toggles the status of the Checkbutton component (checked - > unchecked / unchecked - > checked).

Anchor=W

	from tkinter import *
	
	root = Tk()
	
	GIRLS = ["Jenny","Penny","Lenny","Donny"]
	var = []
	
	for girl in GIRLS:
	    var.append(IntVar())
	    c = Checkbutton(root, text=girl, variable=var[-1])
	    c.pack(anchor=W)
	
mainloop()

RadioButton

In order to implement its "radio selection" behavior, ensure that the variable option of all buttons in a group uses the same variable, and use the value option to specify what value each button represents. When a button is selected, the value of value will be assigned to variable, so as to mutually exclude other values (options)

from tkinter import *

master = Tk()
v = IntVar()
v.set(2)

Radiobutton(master, text="One", variable=v, value=1).pack(anchor=W)
Radiobutton(master, text="Two", variable=v, value=2).pack(anchor=W)
Radiobutton(master, text="Three", variable=v, value=3).pack(anchor=W)
mainloop()

If the indicator option is set to False, the style of Radiobutton will become the style of ordinary button:

method

deselect()

– deselect the button.

flash()

– refresh the Radiobutton component, which redraws the Radiobutton component several times (switching between ACTIVE and NORMAL states).

– this method is very useful during debugging. You can also use this method to remind the user that the button is activated.

invoke()

– call the function or method specified by the command option in Radiobutton and return the return value of the function.

– this method is invalid if the status of the Radiobutton is DISABLED or if the command option is not specified.

select()

– set the Radiobutton component to selected.

LabelFrame

When grouping related components into groups, you can use LabelFrame components, such as a series of Radiobutton components.

	from tkinter import *
	
	root = Tk()
	lf = LabelFrame(root, text='Who is the most butiful girl?', padx=10, pady=10)
	lf.pack(padx=20, pady=20)
	
	GIRLS = [
	    ("Jenny", 1),
	    ("Penny", 2),
	    ("Lenny", 3),
	    ("Donny", 4)
	    ]
	
	v = IntVar()
	v.set(2)
	
	for girl, num in GIRLS:
	    c = Radiobutton(lf, text=girl, value=num, variable=v)
	    c.pack(anchor=W)
	
	mainloop()

Entry (input box)

Entry(master=None, **options) (class)

Finally, the Entry component allows you to specify the position of characters in the following ways:

  • Numeric index number: regular Python index number, starting from 0
  • ANCHOR: corresponding to the first selected character (if any)
  • END: the last position corresponding to the existing text
  • INSERT: corresponds to the current position of the insertion cursor
  • Mouse coordinates ("@x"): X is the horizontal distance between the mouse position and the left edge of the Entry, so that the position of the character can be relatively located by the mouse
optionmeaning
background

1. set the background color of the Entry

2. the default value is specified by the system

bgSame as background
borderwidth

1. set the border width of the Entry

2. the default value is 1 or 2 pixels

bdSame as borderwidth
cursor

1. specify the mouse style when the mouse floats over the Entry

2. the default value is specified by the system

exportselection

1. specify whether the selected text can be copied to the clipboard

2. the default value is True

3. it can be modified to False to indicate that text copying is not allowed

font

1. specify the font of the text in the Entry

2. the default value is specified by the system

foreground

1. set the text color of the Entry

2. the default value is specified by the system

fgSame as foreground
highlightbackground

1. specify the color of the highlighted border when the Entry does not get the focus

2. the default value is specified by the system

highlightcolor

1. specify the color of the highlighted border when the Entry gets the focus

2. the default value is specified by the system

highlightthickness

1. specify the width of the highlighted border

2. the default value is 1 or 2 pixels

insertbackgroundSpecifies the color of the input cursor
insertborderwidth

1. specify the border width of the input cursor

2. if it is set to a value other than 0, the cursor style will be set to RAISED

3. warm tips for small turtle: set insertwidth a little larger to see the effect

insertofftime

1. this option controls the flashing frequency of the cursor (off)

2. the unit is milliseconds

insertontime

1. this option controls the flashing frequency of the cursor (on)

2. the unit is milliseconds

insertwidth

1. specify the width of the cursor

2. the default value is 1 or 2 pixels

invalidcommand

1. specify the function to be called when the content entered in the input box is "illegal"

2. that is, specify the function when the function specified by the validateCommand option returns False

3. for details, please refer to the detailed explanation on verification of small turtle at the bottom of this content

invcmdSame as invalidcommand
justify

1. define how to align text in the input box

2. use LEFT, RIGHT or CENTER

3. the default value is LEFT

relief

1. specify border style

2. the default value is SUNKEN

3. other selectable values are FLAT, RAISED, grove and RIDGE

selectbackground

1. specify the background color when the text of the input box is selected

2. the default value is specified by the system

selectborderwidth

1. specify the border width when the text of the input box is selected (selected border)

2. the default value is specified by the system

selectforeground

1. specify the font color when the text of the input box is selected

2. the default value is specified by the system

show

1. set how the input box displays text content

2. if the value is not empty, the input box will display the specified string instead of the real content

3. if this option is set to "*", it is the password input box

state

1. the status that the entry component can set: NORMAL, DISABLED or "readonly" (note that this is a string. It is similar to DISABLED, but it supports selection and copying, but cannot be modified, and DISABLED is completely DISABLED)

2. the default value is NORMAL

3. note that if this option is set to DISABLED or "readonly", calls to insert() and delete() methods will be ignored

takefocus

1. specify that the Tab key can be used to move the focus to the input box

2. it is on by default. You can set this option to False to avoid the focus in this input box

textvariable

1. specify a Tkinter variable (usually StringVar) associated with the contents of the input box

2. when the contents of the input box change, the value of the variable will change accordingly

validate

1. this option sets whether to enable content verification

2. for details, please refer to the detailed explanation on verification of small turtle at the bottom of this content

validatecommand

1. this option specifies a verification function to verify whether the contents of the input box are legal

2. the validation function needs to return True or False to indicate the validation result

3. note that this option is only valid when the value of validate is not "none"

3. for details, please refer to the detailed explanation on verification of small turtle at the bottom of this content

vcmdJust like validatecommand
width

1. set the width of the input box in characters

2. the default value is 20

3. for a variable width font, the actual width of the component is equal to the average width of the font multiplied by the value of the width option

xscrollcommand

1. associated with the scrollbar component

2. if you think the content entered by the user will exceed the input box width of the component, you can consider setting this option

3. refer to: Scrollbar component [bbs.fishc.com]

method

delete(first, last=None)

– delete all contents within the range of parameters first to last (including first and last)

– if the last parameter is ignored, the option specified by the first parameter is deleted

– use delete(0, END) to delete all contents of the input box

get()

– get the contents of the current input box

icursor(index)

– move the cursor to the position specified by the index parameter

– this also sets the value of INSERT

index(index)

– returns the sequence number of the option corresponding to the index parameter (e.g. e.index(END))

insert(index, text)

– insert the contents of the text parameter into the position specified by the index parameter

– use insert(INSERT, text) to insert the string specified by the text parameter into the cursor position

– use insert(END, text) to insert the string specified by the text parameter to the end of the input box

scan_mark(x)

– use this method to scroll the contents of the input box

– the mouse down event needs to be bound to scan_mark(x) method (x is the current horizontal position of the mouse), and then bind the <motion> event to scan_ The dragto (x) method (x is the current horizontal position of the mouse) enables the input box to be in the current position and sacn_mack(x) specifies horizontal scrolling between positions

selection_adjust(index)

– this method is used to ensure that the selected range in the input box contains the characters specified by the index parameter

– if the selected range already contains this character, nothing will happen

– if the selected range does not contain this character, the selected range will be extended from the cursor position to this character

selection_clear()

– uncheck status

selection_from(index)

– start a new selection

– sets the value of ANCHOR

selection_present()

– returns whether the input box has selected text

– returns True if any, False otherwise

selection_range(start, end)

– set selection range

– the start parameter must be smaller than the end parameter

– using selection_range(0, END) selects all contents of the entire input box

selection_to(index)

– check all contents from ANCHOR to index parameter

xview(index)

– this method is used to ensure that the characters specified by the given index parameter are visible

– scrolls the contents of the input box if necessary

xview_moveto(fraction)

– adjust the visible range of the contents of the input box according to the ratio given by the fraction parameter

– the range of the fraction parameter is 0.0 ~ 1.0, 0.0 indicates the start position of the input box, and 1.0 indicates the end position of the input box

xview_scroll(number, what)

– scroll the visible range of the input box horizontally according to the given parameters

The – number parameter specifies the number of scrolls, and a negative number indicates reverse scrolling

– the what parameter specifies the unit of scrolling, which can be UNITS or PAGES (UNITS represents a character unit, PAGES represents a page)

eg:

	from tkinter import *
	 
	root = Tk()
	 
	label1 = Label(root, text='works:').grid(row=0, column=0, padx=10, pady=10)
	label2 = Label(root, text='author:').grid(row=1, column=0, padx=10, pady=10)
	 
	 
	e1 = Entry(root)
	e1.grid(row=0, column=1, padx=10, pady=10)
	e2 = Entry(root)
	e2.grid(row=1, column=1, padx=10, pady=10)
	 
	 
	def show():
	    print('works: <<%s>> \n author: %s' % (e1.get(), e2.get()))
	    e1.delete(0, END)
	    e2.delete(0, END)
	          
	b1 = Button(root, text='pick up information', width=10, command=show).grid(row=2, column=0, sticky=W, padx=10, pady=10)
	b2 = Button(root, text='sign out', width=10, command=root.quit).grid(row=2, column=1, sticky=E, padx=10, pady=10)
	 
	mainloop()

About verification details

The Entry component supports the verification of the legitimacy of the input content. For example, if a number is required, and you enter a letter, it is illegal. To implement this function, you need to set the validate, validatecommand, and invalidcommand options.

The "switch" that enables validation first is the validate option. The values that can be set for this option are:

valuemeaning
'focus'Validate when the Entry component gains or loses focus
'focusin'Validate when the Entry component gets the focus
'focusout'Validate when the Entry component loses focus
'key'Verify when the input box is edited
'all'Verify when any of the above conditions occurs
'none'

1. turn off the verification function

2. this option is set by default (that is, authentication is not enabled)

3. note that 'None' of the string is not 'None'

The function specified by the invalidcommand option is called only when the return value of validatecommand is False.

Tkinter provides some additional options for validation functions:

Additional optionsmeaning
'%d'Operation code: 0 indicates deletion; 1 indicates insertion operation; 2 indicates that the value of the textvariable variable is modified
'%i'

1. when the user attempts to insert or delete, the line selection indicates the insertion or deletion position (index number)

2. if the verification function is called because the value of the textvariable variable is modified, or the focus is lost, the value is -1

'%P'

1. when the value in the input box is allowed to change, the value is valid

2. this value is the latest text content of the input box

'%s'This value is the text content of the input box before calling the validation function
'%S'

1. this value is valid when the insert or delete operation triggers the verification function

2. this option indicates the inserted and deleted contents of the text

'%v'The value of the current validate option of the component
'%V'

1. reason for calling validation function

2. the value is one of'focusin','focusout','key'or'forced' (the variable value specified by textvariable option is modified)

'%W'Name of the component

To use these options, you can write: validatecommand=(f, s1, s2,...)

Where, f is the name of the verification function "after cooling". s1, s2 and s3 are additional options, which will be passed to the F function in turn as parameters. We just said that it needs to be cooled before using the hidden skill. In fact, we call the register() method to wrap the verification function:

Addition Calculator:

	from tkinter import *
	 
	root = Tk()
	 
	v1 = StringVar()
	v2 = StringVar()
	v3 = StringVar()
	 
	def check(num):
	    return num.isdigit():
	    
	CMD = root.register(check)    
	e1 = Entry(root, textvariable=v1, validate='key', validatecommand=(CMD, '%P'))
	e2 = Entry(root, textvariable=v2, validate='key', validatecommand=(CMD, '%P'))
	e3 = Entry(root, textvariable=v3, state='readonly')
	e1.grid(row=0, column=0, padx=10, pady=10)
	e2.grid(row=0, column=2, padx=10, pady=10)
	e3.grid(row=0, column=4, padx=10, pady=10)
	 
	l1 = Label(root, text='+', font='20').grid(row=0, column=1)
	l2 = Label(root, text='=', font='20').grid(row=0, column=3)
	 
	def calc():
	    total = int(e1.get()) + int(e2.get())
	    v3.set(str(total))
	 
	b = Button(root, text='Calculate', command=calc).grid(row=1, column=2)
	 
	mainloop()

Listbox listbox

Listbox can only contain text items, and all items need to use the same font and color. Depending on the configuration of the component, the user can select one or more options from the list.

listbox. The insert (index number, string) method adds text. Eg, insert (0, 'a') or insert(END, 'b') insert at the end of the previous line

listbox. Delete (index number) eg delete(ACTIVE) delete the selected item (select the last one when multiple items are selected)

selectmode

1. decide which mode to choose

2. four different selection modes: SINGLE, BROWSE (it is also a SINGLE selection, but you can directly change the options by dragging the mouse or using the direction keys), MULTIPLE and EXTENDED (it is also a multi selection, but you need to press and hold the Shift key or Ctrl key or drag the mouse at the same time)

3. the default is BROWSE

xscrollcommand

1. add a horizontal scroll bar to the Listbox component

2. associate this option with the Scrollbar component

yscrollcommand

1. add a vertical scroll bar to the Listbox component

2. associate this option with the Scrollbar component

method:

*yview(*args)

– this method is used to scroll the contents of the Listbox component in the vertical direction. It is generally implemented by binding the command option of the Scollbar component (refer to: Scrollbar [bbs.fishc.com])

– if the first parameter is MOVETO, the second parameter means scrolling to the specified position: 0.0 means the top, 1.0 means the bottom

– if the first parameter is SCROLL, the second parameter indicates the number of scrolls, and the third parameter indicates the unit of scrolling (which can be UNITS or PAGES). For example, yview(SCROLL, 3, PAGES) indicates scrolling down three PAGES

Usually linked with scrollbar to display more items

Scrollbar

The Scrollbar component is usually used almost with the Text component, Canvas component and Listbox component. The horizontal scroll bar can also be used with the Entry component.

To install a vertical scroll bar on a component, you need to do two things:

1. set the set method of the component whose yscrollcommand==Scrollbar

2. set the command option of the Scrollbar component to the yview() method of the component

Analysis: when the visual range of the Listbox component changes, the Listbox component notifies the Scrollbar component by calling the set() method. When the user manipulates the scroll bar, the yview() method of the Listbox component will be called automatically.

The method of adding horizontal scroll bars is the same as the above, except that yscrollcommand is changed to xscrollcommand, and yview is changed to xview.

eg:

	from tkinter import *
	 
	root = Tk()
	f1 = Frame(root)
	f1.pack(side=TOP)
	f2 = Frame(root)
	f2.pack(side=BOTTOM)
	 
	s = Scrollbar(f1)
	s.pack(side=RIGHT, fill=Y)
	 
	lb = Listbox(f1, selectmode=EXTENDED, yscrollcommand=s.set)
	lb.pack(side=LEFT, fill=BOTH)
	 
	for i in range(1000):
	    lb.insert(END, i)
	 
	Button(f2, text='DELETE', command=lambda x=lb:x.delete(ACTIVE)).pack(side=BOTTOM)
	 
	s.config(command=lb.yview)
	 
	mainloop()

Scale component

*Scale(master=None, **options) (class)

frome_ And to scrolling range

tickinterval scale

resolution step (amount adjusted at one time)

Length the length of the scroll bar

get()

– get the position of the current slider

	from tkinter import *
	 
	root = Tk()
	 
	s1 = Scale(root, from_=0, to=50, \
	           tickinterval=5, resolution=3, length=150)
	s1.pack()
	s2 = Scale(root, from_=0, to=100, orient=HORIZONTAL, \
	           tickinterval=10, resolution=20, length=150)
	s2.pack()
	 
	def location():
	    print('VERTICAL: %s \nHORIZONTAL: %s' %(s1.get(), s2.get()))
	Button(root, text='Location', command=location).pack()
	 
	mainloop()

Textcomponent

The Text component is used to display Text documents, including plain Text or formatted Text (using different fonts, embedding pictures, displaying links, even HTML with CSS format, etc.). Therefore, it is often used as a simple Text editor and web browser

To INSERT content, you can use the insert() method and the INSERT or END index number

To insert an object into a Text component, you can use window_create() and image_create() method

The delete() method can be used to delete the contents in the Text component. The following code is used to delete all contents (including window and image objects, but not the contents of marks). The first parameter can be used to delete a single

text.delete(1.0, END)

text.delete(b1)

state is NORMAL by default. If it is set to DISABLED, it means read-only

get() – get content

The index() method is used to convert all supported "index" formats -- > Print (text.index (insert))

	from tkinter import *
	 
	root = Tk()
	 
	text1 = Text(root, width=50, height=40)
	text1.pack()
	 
	text1.insert(INSERT, 'starting writing\n')
	 
	photo = PhotoImage(file='g.gif')
	 
	def show():
	    text1.insert(END, '\nshow a new photo')
	    text1.image_create(END, image=photo)  # insert a photo into textbox after click button
	    
	button = Button(text1, text='Click Me!', command=show)
	 
	# insert a button into the textbox
	text1.window_create(INSERT, window=button)
	 
	mainloop()

– Indexes usage

Indexes are used to point to the position of Text in the Text component. Like the Python sequence index, the Text component index also corresponds to the position between actual characters.

Tkinter offers a number of different index types:

  • "line.column" (row / column)
    • 1.0 – line numbers start with 1 and column numbers start with 0
    • It is allowed to use a line number greater than the current number of lines, and take the next position at the end of the existing content
    • Floating point numbers are allowed to be used. Both "1.2" and "1.6" can be used
    • Use the index() method to convert all supported index formats to index numbers in row / column format.
  • "line.end" (the end of a line)
    • Represents the position of the last character of the line
  • INSERT
    • Corresponds to the position of the insertion cursor.
  • CURRENT
    • Corresponds to the position closest to the mouse coordinate. However, if you press any mouse button, it will not respond until you release it.
  • END
    • The next position of the last character in the Text buffer corresponding to the Text component.
  • user-defined marks
    • INSERT and CURRENT are two pre named marks. In addition, you can customize marks
  • user-defined tags("tag.first","tag.last")
    • User defined tags represent special event bindings and styles that can be assigned to Text components
    • If no such tag is found, Tkinter will throw a TclError exception.
  • selection(SEL_FIRST,SEL_LAST)
    • Is a special tag named sel (or "sel"), which indicates the currently selected range. You can use SEL_FIRST to SEL_LAST to represent this range. If there is no selected content, Tkinter will throw a TclError exception.
  • window coordinate("@x,y")
    • Window coordinates as index, "@%d,%d"% (event.x, event.y) -- find the character closest to the mouse position
  • embedded object name(window,images)
    • Used to point to window and image objects embedded in Text components. To reference a window, simply use a Tkinter component instance as an index.
  • expressions
    • The expression to modify the index is implemented in the form of string.
expressionmeaning
"+ count chars"

1. move the index forward (- >) by count characters

2. the line break character can be crossed, but the position of END cannot be exceeded

"- count chars"

1. move the index backward (< -) by count characters

2. the line feed character can be crossed, but the position of "1.0" cannot be exceeded

"+ count lines"

1. move the index forward (- >) to the count line

2. the index will try to remain in the same column as before the move. However, if there are too few characters in the row after the move, it will be moved to the end of the row

"- count lines"

1. move the index backward (< -) to count row

2. the index will try to remain in the same column as before the move. However, if there are too few characters in the row after the move, it will be moved to the end of the row

" linestart"

1. move the index to the starting position of the row where the current index is located

2. note that there must be a space before using this expression

" lineend"

1. move the index to the end of the row where the current index is located

2. note that there must be a space before using this expression

" wordstart"

1. move the index to the beginning of the word pointed to by the current index

2. a word is defined as a series of letters, numbers, underscores, or any combination of non blank characters

3. note that there must be a space before using this expression

" wordend"

1. move the index to the end of the word pointed to by the current index

2. a word is defined as a series of letters, numbers, underscores, or any combination of non blank characters

3. note that there must be a space before using this expression

TIPS: Keywords can be abbreviated and spaces can be omitted as long as the results are not ambiguous. For example: "+ 5 chars" can be abbreviated to "+5c"

–mark_set() method

Marks are usually invisible objects embedded in the Text of a Text component. In fact, marks specifies the position between characters (which can be understood as an index) and moves along with the corresponding characters. Marks include INSERT, CURRENT and user-defined marks. INSERT and CURRENT are special marks predefined by Tkinter and cannot be deleted.

Insert (or "insert") is used to specify the position of the current insertion cursor. Tkinter will draw a flashing cursor at this position (so not all Marks are invisible).

Current (or "current") is used to specify the position closest to the mouse coordinates. However, if you press any mouse button, it will not respond until you release it.

You can also customize any number of Marks. The names of Marks are composed of ordinary strings and can be any character except white space. Using mark_ The set () method creates and moves Marks.

If you insert or delete text before the position of a Mark, Mark will move along with it (if you insert a character, Mark will move back one character).

  • By default, the content is inserted into mark. It is inserted to the LEFT of mark_ When gravity is LEFT, it is inserted to the right. It feels that the default mark will 'Remember' the position of the following elements. Mark_ When gravity is LEFT, that is the element position before 'Remember'.
  • The only way to delete Marks is to use mark_unset() method. Deleting the text around the mark will not delete the mark itself (when all elements around the mark are deleted, they will be initialized to 1.0).

	from tkinter import *
	 
	root = Tk()
	 
	text = Text(root, width=50, height=30)
	text.pack()
	 
	text.insert(INSERT, 'starting writing')
	text.mark_set('here', '1.3', )
	#text.mark_gravity('here', LEFT)
	text.insert('here', 'GOD')
	text.insert('here', 'GUN')
	 
	text.mark_unset('here') # clear the mark
	text.insert('here', 'CAR')  # TclError: bad text index "here" as mark had gone
	 
	mainloop()

– tags usage

Tags are usually used to change the style and function of the content in the Text component. You can change the font, size and color of the Text. In addition, tags allows you to associate Text, embedded components, and images with events such as keyboard and mouse. In addition to user-defined tags, there is also a predefined special Tag:sel (or "sel" to represent the corresponding selected content)

Creation method:

text.insert(INSERT, "I love this iphone13")

text.tag_add("tag1", "1.7", "1.12", "1.14") \

text.tag_config("tag1", background="yellow", foreground="red")

Note: you can directly use tag_config() to create a nonexistent tag, but the scope cannot be specified

Tag_config() parameter

optionmeaning
background

1. specify the background color of the content described by the Tag

2. note: bg is not the abbreviation of this option. Here bg is interpreted as the abbreviation of the bgsticky option

bgstipple

1. specify a bitmap as the background and fill it with the color specified by the background option

2. this option will take effect only when the background option is set

3. the default standard bitmaps are:'error','gray75','gray50','gray25','gray12','hourglass','info','questionhead','question'and'warning'

borderwidth

1. specify the width of the text box

2. the default value is 0

3. this option will not take effect until the relief option is set

4. note: bd abbreviation cannot be used for this option

fgstipple

1. specify a bitmap as the foreground color

2. the default standard bitmaps are:'error','gray75','gray50','gray25','gray12','hourglass','info','questionhead','question'and'warning'

fontSpecifies the font used for the content described by the Tag
foreground

1. specify the foreground color of the content described by the Tag

2. note: fg is not the abbreviation of this option. Here fg is interpreted as the abbreviation of fgticket option

justify

1. control text alignment

2. the default is LEFT. You can also select RIGHT and CENTER

3. note: this option can only take effect if Tag points to the first character of the line

lmargin1

1. set the indent of the first line of the text block pointed to by Tag

2. the default value is 0

3. note: you need to point Tag to the first character of the text block or the entire text block to make this option effective

lmargin2

1. set the indent of the text block pointed to by Tag except the first line

2. the default value is 0

3. note: you need to point Tag to the entire text block to make this option effective

offset

1. set the offset distance of the text pointed by Tag from the baseline

2. you can control whether the text increases (positive value) or decreases (negative value) relative to the baseline

3. the default value is 0

overstrike

1. draw a strikethrough the text range specified by Tag

2. the default value is False

relief

1. specify the border style of the text in the corresponding range of Tag

2. the available values are: sunken, raised, grove, ridge or FLAT

3. the default value is FLAT (no border)

rmargin

1. set the indent on the right side of the text block pointed to by Tag

2. the default value is 0

spacing1

1. set the space between each line in the text block described by Tag and the upper blank

2. note: automatic line feed does not count

3. the default value is 0

spacing2

1. set the space between lines of the text block described by Tag

2. note: line breaks ('\n') do not count

3. the default value is 0

spacing3

1. set the space between each line in the text block described by Tag and the space below

2. note: automatic line feed does not count

3. the default value is 0

tabs

1. customize the function of Tab key in the text block described by Tag

2. the default Tab is defined as the width of 8 characters

3. you can also define multiple Tab stops: tabs= ('3c','5c','12c') means that the first three tabs are 3cm, 5cm and 12cm wide respectively. The next tabs are calculated according to the difference between the last two tabs, that is, 19cm, 26cm and 33cm

4. you should note that 'c' above it means "cm" instead of "character". You can also select units of'i'(inch),'m' (millimeter) and'p'(DPI, about'1i' equals'72p')

5. if it is an integer value, the unit is pixel

underline

1. if this option is set to True, the text within the range described by Tag will be underlined

2. the default value is False

wrap

1. set whether to wrap a line of text automatically when its length exceeds the width set by the width option

2. the values of this option can be: NONE (no line wrapping), CHAR (line wrapping by character) and WORD (line wrapping by WORD)

If you add multiple Tags to the text in the same range and set the same options, the newly created Tag style will overwrite the older tag:

tag_raise() / tag_lower() can change the priority

tag supports event binding, see the example

tag_bind('tag_name', '<event_name>', command)

Remove tag:

tag_delete(*tagNames) – deletes the Tags specified by tagNames

tag_remove(tagName, index1, index2=None)

– delete all tagnames between index1 and index2

– if the index2 parameter is ignored, only the tagName (if any) of the character specified by index1 will be deleted

	from tkinter import *
	import webbrowser
	
	root = Tk()
	t1 = Text(root, width=40, height=20)
	t1.pack()
	t1.insert('1.0', 'Iceberg Right Head!')
	
	#Create two tag s
	t1.tag_config('tag1', background='black', foreground='yellow')
	t1.tag_config('tag2', background='gray')
	
	# The new tag has higher priority than the old one, and the available tag_raise() or tag_lower() change priority
	t1.insert(END, 'click me to escape', ('tag1', 'tag2')) # Background will display blue
	
	# Create a new tag for click me
	t1.tag_add('tag3', '1.19', '1.27', '1.30', '1.32') 
	t1.tag_config('tag3', underline=True)
	
	def show_hand_cursor(event):
	    t1.config(cursor='arrow')
	
	def show_arrow_cursor(event):
	    t1.config(cursor='xterm')
	
	def click(event):
	    webbrowser.open('www.zhihu.com')
	
	#Binding events
	t1.tag_bind('tag3', '<Enter>', show_hand_cursor)
	t1.tag_bind('tag3', '<Leave>', show_arrow_cursor)
	t1.tag_bind('tag3', '<Button-1>', click)
	
	mainloop()

Text.Get() - get text content

eg: via hashlib MD5 - detect content changes

	from tkinter import *
	import hashlib
	
	root = Tk()
	text = Text(root, width=20, height=10)
	text.pack()
	
	text.insert('1.0', 'Love is burn into peace')
	
	contents = text.get('1.0', END)
	
	def getSig(contents):
	    m = hashlib.md5(contents.encode())
	    return m.digest()
	
	org = getSig(contents)
	
	def check():
	    new_content = text.get('1.0', END)
	    if org != getSig(new_content):
	        print('Things have changed, be careful traitor!')
	    else:
	        print('Everything remains the same~')
	
	Button(root, text='Audit', command=check).pack()
	
	mainloop()

Text.Search()

*search(pattern, index, stopindex=None, forwards=None, backwards=None, exact=None, regexp=None, nocase=None, count=None)

– search for pattern from index to stopindex (if not specified, search to the end)

– if it is found successfully, return the first matching character with "line.column"; Otherwise, an empty string is returned

The – forwards parameter is set to True to search forward (- >)

– setting the backwards parameter to True means searching backwards (< -)

– if the exact parameter is set to True, it means that the search results exactly match the pattern

– if the regexp parameter is set to True, the pattern is interpreted as a regular expression in Tcl format

– set the nocase parameter to True to ignore case, and the default is case sensitive search

– the count parameter is specified as a Tkinter variable of an IntVar, which is used to store the number of characters when a match is found (if there is no embedded image or window object in the matching result, this value is generally equal to the number of characters of pattern)

Eg: find string

	from tkinter import *
	
	root = Tk()
	text = Text(root, width=20, height=10)
	text.pack()
	
	text.insert('1.0', 'Love is burn into peace')
	
	def getIndex(text, inx):
	    return tuple(map(int, text.index(inx).split('.')))
	
	start = '1.0'
	while True:
	    loc= text.search('o', start, stopindex=END) #Return line after finding the first result Num and stop
	    if not loc: #Terminate loop when result is not found
	        break
	    print('found it in ', getIndex(text, loc))
	    start = loc + '+1c'  #Move one byte backward to continue searching
	    
	mainloop()

Revocation and reinstatement

The Undo function of the Text component can be enabled by setting the undo option to True. Then use edit_undo() method implements the "undo" operation, using edit_ The redo () method implements the "restore" operation.

This is because there is a stack inside the Text component dedicated to recording each change of content, so each "undo" operation is a stack popping operation, and "restore" is a stack pressing operation again.

By default, each complete operation is put on the stack. But how is it a complete operation? Tkinter thinks that the operations before each focus switch, the user pressing the Enter key, and the conversion of delete \ insert operations are a complete operation. That is to say, if you continuously input "FishC is a P", a "undo" operation will delete all the contents.

The method is to first set the autoseparators option to False (because this option allows Tkinter to automatically insert a "separator" after a complete operation is considered to be over), then bind keyboard events, and use edit every time there is input_ The separator () method artificially inserts a "separator", so that inserting a character is a complete operation, and then each time you click "undo", one character will be removed.

*edit_redo(self)

– redo the last undo operation

– this method is invalid if undo option is False

– for details, see the above usage ["undo" and "restore" operations]

*edit_separator()

– insert a "separator" into the stack where the operation record is stored to indicate that a complete operation has been completed

– this method is invalid if undo option is False

– for details, see the above usage ["undo" and "restore" operations]

*edit_undo()

– undo the last operation

– this method is invalid if undo option is False

– for details, see the above usage ["undo" and "restore" operations]

EG:

	from tkinter import *
	import hashlib
	
	root = Tk()
	# 'undo=True'activate undo / restore function
	# 'autoseparators=False'turn off the autoseparator setting
	text = Text(root, width=30, height=10, undo=True, autoseparators=False, maxundo=10)
	text.pack()
	
	def typing(event):
	    text.edit_separator()
	
	def undo():
	    text.edit_undo()
	
	def redo():
	    text.edit_redo()
	
	text.bind('<Key>', typing) #Bind keyboard keys and set separator for each click to facilitate undo/redo
	text.insert('1.0', 'Love is burn into peace')
	
	Button(root, text='UNDO', command=undo).pack()
	Button(root, text='REDO', command=redo).pack()
	
	mainloop()

Canvas components

The canvas component provides the basis for Tkinter's graphic rendering. Canvas is a highly flexible component. You can use it to draw graphs and charts, create graph editors, and implement various custom widgets.

– draw images as you like

Canvas(root, width=100, height=100) unit pixel

Created objects are retained until they are modified

Modification method:

w.coords() move object

w.itemcofig() set object properties

w.delete() delete object

anvas component support object*

  • Arc (arc, chord or sector)
  • Bitmap (built-in bitmap file or XBM format file)
  • image (instance object of BitmapImage or PhotoImage)
  • line
  • Oval (round or oval)
  • polygon
  • rectangle
  • Text (text)
  • window (component)
    Among them, chord, fan, ellipse, circle, polygon and rectangle, which are "closed" shapes, are composed of contour lines and fill colors, but can be set to transparent (passing in an empty string means transparent).

Common creation methods:

Create_line(x1,y1,x2,y2,dash=(4,4), fill= 'blue') – straight line, dotted line (specify dash)

Create_rectangle() – rectangle, adding diagonal coordinates

Create_oval() – ellipse, which is drawn with rectangular coordinates, and circle with square coordinates

Create_text(x,y, text= 'F') -- coordinate of font center point

create_arc(bbox, **options) – create a pie, bow, or ARC based on bbox (x1, y1, x2, y2)

style

1. specify whether this method creates a sector (PIE), bow (CHORD), or arc (ARC)

2. the sector is created by default

create_polygon(coords, **options) – draws a polygon according to the coordinates given by coords

Coordinate system

Since the Canvas may be larger than the window (Canvas component with scroll bar), the Canvas component can choose to use two coordinate systems:

  • Window coordinate system: take the upper left corner of the window as the coordinate origin

  • Canvas coordinate system: take the upper left corner of the canvas as the coordinate origin
    To convert the window coordinate system to the canvas coordinate system, you can use the canvasx() or canvasy() methods:

    def callback(event):
        canvas = event.widget
        x = canvas.canvasx(event.x)
        y = canvas.canvasy(event.y)
        print canvas.find_closest(x, y)
    

Object display order:

All Canvas objects created in the Canvas component will be listed in the display list,

By default, the newly created canvas object will overwrite the overlapped part of the old canvas object, that is, the canvas object above the display list will overwrite the one below). Of course, canvas objects in the display list can be reordered.

Specify canvas object

The Canvas component provides several methods for you to specify Canvas objects:

  • Item handles (ID of the unique canvas object automatically created by Tkinter - integer)
  • Tags (similar to text tags but owned only by canvas objects)
  • All (all objects in canvas)
  • CURRENT (canvas object under the mouse pointer (if any))

EG: draw five pointed star (outline, fill)

"2 * PI / 5" is expressed in radians.

Note: about the difference between radian and degree

The definition of "degree" is that "two rays are emitted from the center of the circle to the circumference, forming an arc with an included angle and an included angle directly opposite. When the arc length is exactly equal to one 360 of the circumference of the circle, the included angle of the two rays is 1 degree. (as shown in Figure 1)

The definition of "radian" is: two rays are emitted from the center of the circle to the circumference, forming an arc with an included angle and an included angle directly opposite. When the arc length is exactly equal to the radius of the circle, the included angle of the two rays is 1 radian. (as shown in Figure 2)

The definitions are similar, except that the arc length of the angle pair is different. The arc length corresponding to 1 degree is equal to 1/360 of the circumference of the circle, while the arc length corresponding to 1 degree is equal to the radius.

Their relationship can be expressed and calculated as follows:

Angle (radian) = arc length / radius

The circumference of a circle is 2 π times the radius, so a circumference (360 degrees) is 2 π radians.

The length of a semicircle is π times the radius, so a flat angle (180 degrees) is π radians.

< reference from https://www.jianshu.com/p/2823a0b18278>

	from tkinter import *
	import math as m
	
	root = Tk()
	
	w = Canvas(root, width=480, height=320, background='red')
	w.pack()
	
	# Center (x, y) and radius r
	def draw_star(r, x, y):
	    # Coordinates of each point
	    points = [
	        # top left corner
	        x-int(r * m.sin(2 * m.pi / 5)), \
	        y-int(r * m.cos(2 * m.pi / 5)), \
	        # Upper right corner
	        x+int(r * m.sin(2 * m.pi / 5)), \
	        y-int(r * m.cos(2 * m.pi / 5)), \
	        # lower left quarter
	        x-int(r * m.sin(m.pi / 5)), \
	        y+int(r * m.cos(m.pi / 5)), \
	        # vertex
	        x, \
	        y-r, \
	        # Lower right corner
	        x+int(r * m.sin(m.pi / 5)), \
	        y+int(r * m.cos(m.pi / 5)), \
	        ]
	
	    star = w.create_polygon(points, fill='yellow')
	
	draw_star(96, 160, 160)
	draw_star(32, 320, 64)
	draw_star(32, 384, 128)
	draw_star(32, 384, 224)
	draw_star(32, 320, 288)
	
	mainloop()

EG: making Sketchpad

Tips: create small dots through the smallest square (Canvas cannot draw dots directly), bind the left mouse button (<b1 motion>, paint)

	from tkinter import *
	import math as m
	
	root = Tk()
	
	w = Canvas(root, width=500, height=400)
	w.pack()
	
	def paint(event):
	    x1, y1 = (event.x - 1), (event.y - 1)
	    x2, y2 = (event.x + 1), (event.y + 1)
	    w.create_oval(x1, y1, x2, y2, fill='red')
	
	# Bind left mouse button event (mouse B1 left, B2 middle, B3 right)
	w.bind('<B3-Motion>', paint)
	
	# Create a button to clear the palette
	Button(root, text='CLEAR', command=lambda x=ALL:w.delete(x)).pack(side=BOTTOM)
	Label(root, text='Please hold the mouse button and move!').pack(side=BOTTOM)
	
	mainloop()

EG: painting Doraemon

	''' Draw a Doraemon '''
	
	from tkinter import *
	import math as m
	
	root = Tk()
	
	w = Canvas(root, width=450, height=450, background='white')
	w.pack()
	
	def oval(x1, y1, x2, y2, color):
	    w.create_oval(x1, y1, x2, y2, fill=color)
	
	def line(x1, y1, x2, y2, color):
	    w.create_line(x1, y1, x2, y2, fill=color)
	
	
	def rect(x1, y1, x2, y2, color):
	    w.create_rectangle(x1, y1, x2, y2, fill=color)
	    
	# Head
	oval(140, 90, 320, 270, 'blue')
	# face
	oval(160, 130, 300, 270, 'white')
	# eyes
	oval(200, 100, 230, 140, 'white')
	oval(230, 100, 260, 140, 'white')
	oval(215, 110, 225, 130, 'black')
	oval(235, 110, 245, 130, 'black')
	oval(218, 115, 222, 127, 'white')
	oval(238, 115, 242, 127, 'white')
	# nose
	oval(223, 135, 238, 150, 'red')
	# whisker
	line(175, 150, 210, 160, 'black')
	line(245, 160, 280, 150, 'black')
	line(170, 175, 210, 175, 'black')
	line(245, 175, 285, 175, 'black')
	line(175, 200, 210, 190, 'black')
	line(245, 190, 280, 200, 'black')
	line(230, 150, 230, 220, 'black')
	# mouth
	w.create_arc(165, 100, 300, 220, style=ARC, start=225)
	
	
	# body
	rect(165, 240, 295, 370, 'blue')
	oval(180, 235, 280, 335, 'white')
	w.create_arc(190, 260, 270, 320, fill='', style=ARC, start=180)
	w.create_arc(190, 260, 270, 320, fill='', style=ARC, start=270)
	line(190, 290, 270, 290, 'black')
	
	# neck
	w.create_line(160, 240, 300, 240, width=15, fill='red', capstyle=ROUND)
	# ring
	oval(220, 240, 240, 260, 'yellow')
	w.create_line(220, 250, 240, 250)
	w.create_line(220, 252, 240, 252)
	oval(227, 255, 232, 260, 'black')
	
	# feet
	oval(150, 350, 220, 390, 'white')
	oval(240, 350, 310, 390, 'white')
	w.create_arc(215, 365, 245, 430, style=CHORD, start=45, fill='white')
	line(215, 375, 245, 375, 'white')
	
	# left hand
	w.create_polygon(167, 245, 130, 280, 130, 300, 167, 280, fill='blue')
	oval(110, 280, 140, 310, 'white')
	# right hand
	w.create_polygon(293, 245, 325, 280, 325, 300, 293, 280, fill='blue')
	oval(315, 280, 345, 310, 'white')
	
	# body fixes
	line(165, 270, 165, 290, 'black')
	line(295, 270, 295, 290, 'black')
	
	
	mainloop()

Menu

Top level menu – first create a menu instance, and then use the add() method to add commands and other submenus

root = Tk()

menubar = Menu(root)

menubar.add_command(label='File', command=xxx)

NOTE: since this component is implemented by the underlying code, it is not recommended that you implement the menu function through buttons and other components.

Submenus – the creation method is similar. The main difference is that they need to be added to the main menu (not the window).

Filemenu=Menu(menubar, tearoff=FALSE) - Tearoff indicates whether to pop up the menu to a separate window

Pop up menu - the creation method is the same, but you need to use the post() method to explicitly display it, and you need to bind the mouse event to a frame

Menubutton() – this component is applicable to the earlier versions of Tkinter when you want menu buttons to appear in other locations

Create a Menubutton component and create a Menu component associated with it

OptionMenu (selection menu) -- a revision of the pull-down menu. Its invention makes up for the regret that the Listbox component cannot implement the pull-down list box.

Add a list to optionmenu and unpack with *[list]

Note: the asterisk (*) is used as a formal parameter to "package". On the contrary, it is used as an argument to "unpack".

As can be seen from the output of the two examples:

When the parameter shape is like *args, any argument passed to the function will be packed into a tuple by position;

	def fun1(*args):      
	        print(type(args))
        	print(args)

When the parameter shape is * * args, any key = value argument passed to the function will be wrapped into a dictionary (dict).

	def fun2(**args):
	        print(type(args))
        	print(args)

If there is packaging, there is unpacking. Unpack the list, tuple or dict by adding an asterisk (*) or two asterisks (* *) before the arguments

	>>> a = [1, 2, 3, 4, 5]
	>>> fun1(*a)
	(1, 2, 3, 4, 5)
	>>> c = {'one':1, 'two':2, 'three':3}
	>>> fun2(**c)
	{'two': 2, 'one': 1, 'three': 3}
	 
	EG:
	from tkinter import *
	
	root = Tk()
	
	menubar = Menu(root) # Create a menu instance
	
	def callback():
	    print('Workhuman!')
	
	# Create hierarchy menu
	filemenu = Menu(menubar, tearoff=False)
	filemenu.add_command(label='Open', command=callback)
	filemenu.add_command(label='Save', command=callback)
	filemenu.add_separator()
	filemenu.add_command(label='Quit', command=root.quit)
	menubar.add_cascade(label='File', menu=filemenu) # Context parent menu
	
	# The hierarchical menu contains checkbutton s
	var = IntVar()
	var1 = IntVar()
	helpmenu = Menu(menubar, tearoff=True)
	helpmenu.add_checkbutton(label='Online Help', variable=var, command=callback)
	helpmenu.add_checkbutton(label='About', variable=var1, command=root.quit)
	menubar.add_cascade(label='Help', menu=helpmenu)
	
	# Right click Popup
	popupmenu = Menu(root)
	def popup(event): # Bind click event
	    popupmenu.post(event.x_root, event.y_root)
	
	    # Contains radiobutton
	var2 = IntVar()
	popupmenu.add_radiobutton(label='Copy', variable=var2, value=1, command=callback)
	popupmenu.add_radiobutton(label='Delete', variable=var2, value=2, command=callback)
	popupmenu.add_radiobutton(label='Paste', variable=var2, value=3, command=callback)
	
	frame = Frame(root, width=300, height=200)
	frame.pack()
	frame.bind('<B3-Motion>', popup)
	
	# Create menu key menubutton in page
	mb = Menubutton(root, text='Click me', relief=RAISED, width=10, height=5)
	mb.pack()
	
	mm = Menu(mb, tearoff=False)
	mm.add_command(label='Who', command=callback)
	mm.add_command(label='Why', command=callback)
	mb.config(menu=mm)
	 
	# Create optional menu optionmenu
	cars = [
	    'Fradi',
	    'Audi',
	    'Benz',
	    'BMW',
	    'Bugadi'
	    ]
	var3 = StringVar()
	var3.set(cars[2])
	om = OptionMenu(root, var3, *cars) # Unpack
	om.pack()
	
	def getvalue():
	    print(var3.get())
	
	Button(text='Get', command=getvalue).pack()
	
	
	root.config(menu=menubar)
	mainloop()

Tags: Python GUI Tkinter programming language

Posted by edkellett on Sat, 04 Jun 2022 03:09:54 +0530