Python tkinter based GUI programming

tkinter is Python's standard GUI Library ("Tk interface"). Python uses tkinter to quickly create GUI applications.

Since tkinter is built into the python installation package, you can import tkinter library as long as Python is installed. Moreover, IDLE is also written with tkinter, which can cope with simple graphical interface easily.

Load tkinter module

import tkinter
inport tkinter as tk
from tkinter import *

The difference between the three is: the second loading method is equivalent to renaming tkinter; The third loading method is to load all the attributes of tkinter module, so you can directly use the attribute name of tkinter module.

import tkinter
win=tkinter.Tk()                 #Create main window
import tkinter as tk
win=tk.Tk()                      #Create main window
from tkinter import *
win=Tk()                         #Create main window

Tk(): create application main window

from tkinter import *
win = Tk()  #Create main window

Example code analysis:

  1. First line: load tkinter
  2. The second line: create a main window using tkinter module's Tk() method, and win is the handle of this window. If the user calls the TK () method multiple times, multiple main windows can be created.

The window created by the above program is very simple and needs to be further improved, that is, setting the title, window size, background color, whether the window is variable, etc. for details, please refer to the following instructions:

Set window title

win.title('My window')

Customize the size and location of the window

win.geometry('500x300')  # The multiplication here is a lowercase x, (length x width) in pixels

width, height = 500, 300
place_x, place_y = 100, 100 #The position starts at the upper left corner of the screen (0,0)
win.geometry(f'{width}x{height}+{place_x}+{place_y}')  
# win.geometry('500x300+100+100')

Set window background color

win.config(bg='black')

Hide outside of window

win.overrideredirect(True)

Fixed window size

win.resizable(0, 0)
# Or it can be written like this:
win.resizable(False, False)
#Set whether the window can be variable in length and width. True: variable, False: immutable
win.resizable(width=False, height=True)

Set the minimum | maximum size of the window

win.minsize(width,height) #Minimum size
win.maxsize(width,height) #Maximum size

Close the window 4 seconds after it is created

win.after(4000, win.destroy)
after() Use format of function: win.after(time, function)
time The time to wait after the window is created, in milliseconds(4000 Milliseconds is 4 seconds)
function It can be a defined function(You can't put parentheses after it),It can also be lambda expression

Main window cycle display

win.mainloop()
Note that loop means loop, win Mainloop will let win refresh constantly
If there is no mainloop, it is a static win, and the value passed in will not have a loop
mainloop is equivalent to a while loop. while True is updated every time you click, so we must have a loop
All window files must have a similar mainloop function. Mainloop is the key of window files.

If required: set the main window to be centered on the screen

from tkinter import *

#Initialize Tk()
win = Tk()

#Set title
win.title('Python GUI Learning')

#Set window size
width = 380
height = 300

#Get the screen size to calculate the layout parameters so that the window is in the center of the screen
screenwidth = win.winfo_screenwidth()
screenheight = win.winfo_screenheight()

#Place window
str= '%dx%d+%d+%d' % (width, height, (screenwidth-width)/2, (screenheight-height)/2)
win.geometry(str)

Tkinter controls (components, widgets)

Some of the following contents are compiled from the blog:
https://www.cnblogs.com/shwee/p/9427975.html#D15

Windows alone cannot realize interaction, and controls are also required. Tkinter provides various controls that can be used in a GUI application. These controls are usually called components or parts. Tkinter supports 16 core widgets.

Frame(): create a control container that can be attached to the window
TopLevel(): create pop-up window

Tkinter classControl nameexplain
FrameframeIt is used to host and place other GUI elements, which is a container
LabellabelDisplays non editable text or images in the specified window
ButtonButtonDisplay buttons in the program, which can contain text or images

Common attributes:

  1. anchor: defines the position of the control in the window or the position of text information in the control
  2. background(bg): defines the background color of the control

The parameters in the control are keyword parameters, which are composed of key values.
Keyword parameters do not have to be passed in order during the transfer process. Parameters in the form of "transfer parameter name = transfer parameter value" are provided.

Label control (label)

The syntax format is as follows:

w = Label ( master, option, ... )
#master: the parent container of the framework.
#Options: optional, that is, the settable properties of the label. These options can be set in the form of key value and separated by commas.

Common options:

bg: label background color;
Text: set text, which can contain line breaks (\ n);
Font: set font;
Image: sets the label image.

Sample code (text display)

import tkinter as tk  
 
#Instantiate an object and create a window
window = tk.Tk()
 
window.title('My Window')
window.geometry('500x300')
 
#Set label in window
label= tk.Label(window, text='Hello! this is Tkinter', bg='green', font=('Arial', 12), width=30, height=2)
# Note: bg is the background, font is the font, width is the length and height is the height. Here, the length and height are the length and height of characters. For example, height=2 means that the label is as high as two characters
 
#Place label
label.pack()
# Label content area placement position, automatic size adjustment
# The methods of placing labels are as follows: 1) label pack();  2)label. place();
 
#Main window cycle display
window.mainloop()

Operation results:

Example code (image display)

import tkinter as tk  
 
#Instantiate an object and create a window
window = tk.Tk()
 
window.title('My Window')
window.geometry('500x300')
 
#import picture
photo=tk.PhotoImage(file='c.gif')

#Set label in window
PhotoLabel=tk.Label(window, image=photo)

#Place label
PhotoLabel.pack()

 
#Main window cycle display
window.mainloop()

Operation results:

When displaying images with Label controls, you should pay attention to:

  1. Tkinter can only load GIF pictures, that is, the extension is GIF image file. Because Tkinter Photoimage() only supports GIF. Otherwise, an error will be reported, similar to:_ tkinter.TclError: couldn’t recognize data in image file “xxx.jpg”.
  2. The imported gif graph is a still image.
  3. When using the PhotoImage function alone, the following problems occur:
import tkinter as tk
photo = tk.PhotoImage(file='c.gif')

RuntimeError: Too early to create image: no default root window

Refer to the blogger's answer: 
google Solutions found:
You forgot to declare root - root = Tk().The Tk system must be ON before using it.
Immediate use PhotoImage()You should declare a Tk(Toplevel (also possible)
Copyright notice: This article is CSDN Blogger「John__wang」Original articles, follow CC 4.0 BY-SA Please attach the original copy of this Agreement and the link.
Original link: https://blog.csdn.net/John__wang/article/details/22325881

Button control (button)

The Button widget is a standard Tkinter widget used to implement various buttons. Buttons can contain text or images and can be associated with a Python function or method. The button can be used to monitor user behavior. When the button is pressed, Tkinter automatically calls the associated function or method.

The syntax format is as follows:

w = Button ( master, option=value, ... )
#master: the parent container of the button.
#Options: optional, that is, the settable properties of the button. These options can be set in the form of key = value and separated by commas.

Common options:

bg: button background color;
Text: set text;
Font: set font; the button can only display one font;
command: the function associated with the button. When the button is clicked, the function will be executed;
padx: the padding of the button in the x-axis direction, which refers to the distance between the content of the button and the edge of the button;
Pad: the inner margin of the button in the y-axis direction (padding)

Example code:

from tkinter import *
win = Tk()
#The horizontal distance between the text and the border is 20 pixels
Button(win, padx=20, text="close", command=win.quit).pack()
#b=Button(win, padx=20, text = "close", command=win.quit)
#b.pack()
win.mainloop()

Entry control (input)

Entry is a single line text string input field provided in tkinter class. It is used to input and display a line of text and collect keyboard input.
When users need to input user information, such as when we usually use software and log in to the web page, the user interaction interface allows us to log in to the account information, etc.
Note:
If you need to enter multiple lines of Text, you can use the Text component.
If you need to display one or more lines of text and you are not allowed to modify it, you can use the Label component.

The syntax format is as follows:

w = Entry( master, option, ... )
master: The parent container of the button.
options: Optional, that is, the settable properties of the button. These options can be selected with the = Values, separated by commas.

Common options:

bg: background color of input box;
Font: set font;
Cursor: cursor shape setting, such as arrow, circle, cross, plus, etc;
Show: specify that the content of the text box is displayed as characters, and the value is arbitrary, which can meet the characters. For example, the password can be set to show = "*";

Example code:

import tkinter as tk
 
# Instantiate an object and create a window
window = tk.Tk()
 window.title('My Window')
window.geometry('500x300')  # The lowercase x is here
 
# Set the input box control entry on the graphical interface and place it
e1 = tk.Entry(window, show='*', font=('Arial', 14))   # Display as ciphertext
e2 = tk.Entry(window, show=None, font=('Arial', 14))  # Display in clear text
e1.pack()
e2.pack()
 
# Main window cycle display
window.mainloop()

Text control (text)

The Text component is used to display and process multiline Text. When creating a Text component, there is no content in it. To insert content into it, you can use insert(). In the Text box displayed after the program runs, you can also enter new Text through the keyboard.

import tkinter as tk

window = tk.Tk()
window.title('My Window')
window.geometry('500x300') 
 
# Set the input box control entry box on the graphical interface and place it
e = tk.Entry(window, show = None)  #Display in clear text
e.pack()
 
# Define the function insert when two events are triggered_ Point and insert_end
#Note: because Python executes from top to bottom, the function must be placed above the button

##The INSERT index indicates an INSERT at the cursor
def insert_point(): # Insert input at mouse focus
    var = e.get()
    t.insert('insert', var)
#The END index number indicates the last insertion
def insert_end():   # Insert the input at the end of the text box
    var = e.get()
    t.insert('end', var)
 
# Create and place two buttons to trigger two situations respectively
b1 = tk.Button(window, text='insert point', width=10,
               height=2, command=insert_point)
b1.pack()
b2 = tk.Button(window, text='insert end', width=10,
               height=2, command=insert_end)
b2.pack()
 
# Create and place a multi line text box for display. Specify height=3 as the text box is three characters high
t = tk.Text(window, height=3)
t.pack()
 
# Main window cycle display
window.mainloop()

The function of this program is to read the contents of the input box into the text box (using the insert() function).

The article on the properties of text controls is quite straightforward:
Copyright notice: This article is the original article of CSDN blogger "Fenghua Mingyuan", which follows the CC 4.0 BY-SA copyright agreement. Please attach the original source link and this notice for reprint.
Original link:
https://blog.csdn.net/weixin_42272768/article/details/100725243

There is a simpler one:

from tkinter import *

root = Tk()

text1 = Text(root,width=30,height=2)
text1.pack()
text1.insert(INSERT,'I love you')

def show():
     print('Yell, I was ordered')
#TextYou can also insert buttons, pictures, etc
b1 = Button(text1,text='Order me order me',command=show)

#Command to create component in text
text1.window_create(INSERT,window=b1)

mainloop()

Operation results:

Geometry management

Three placement methods of window controls

Geometric methoddescribe
pack()
grid()
place()

Subsequent updates~

Keywords: Python

Added by and1c on Sun, 20 Feb 2022 16:02:34 +0200