This article is about how to use tinker Make an incomplete summary 1’ 2.
Tkinter
What is it? ?Tkinter
It's using python
The module of window design .Tkinter
modular (Tk
Interface ) yes Python
Standards for Tk
GUI Interface to toolkit . As python
specific GUI Interface , It's a window of images , tkinter
yes python
Self contained , Can be edited GUI Interface , Used to start , Be familiar with the use of windows , Very necessary .
install python3.7
.
Install editor , The demo uses Pycharm
.
The system version used is macOS Big Sur Version 11.4
.
import tkinter as tk
root = tk.Tk()
# Tk() The function of is to create a window
If you just execute the above two sentences of code , Running the program is unresponsive , Because there is only one main function , There will be no after the execution from top to bottom , The window also disappeared very quickly , So now all we have to do is make the window always show , So we can add a loop
The name of the created window is root
, So we'll use this later root
You can operate this window .
root.mainloop()
Carry out the above 3 Sentence code , We can see the window
root.title(' Window title ')
root.geometry("300x100+630+80")
# Long x wide +x*y, Set the length and width of the window and the position of the window on the screen
call Button()
You can create this component , We assign a constant value to the created component , Later, we can use this constant to operate the button :
btn1 = tk.Button(root)
# Put the button we created in this window root above
btn1["text"] = " Click on "
# Give the button a name ‘ Click on ’
btn1.pack()
# The button component we created , It has been put in the window , But where in the window , We can use it
# pack() To locate ( Other positioning methods will be introduced later )
Create a pop-up window for a button click event , First import messagebox, This must be imported separately
from tkinter import messagebox
def test(e):
messagebox.showinfo(" Window name "," Click success ")
Now there are buttons , There's a way , What I want to do is click a button , Just execute this method , Then you need to bind the button and method , There is a method in the button component bind()
This method can implement binding
btn1.bind("<Button-1>",test)
# The first parameter is zero : The event of pressing the left mouse button The second parameter is : The name of the method to execute
# perhaps
# btn1 = tk.Button(root, text=' Click on ', command=test)
The full code is shown below :
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
root.title(' Window title ')
root.geometry("300x100+630+80")
btn1 = tk.Button(root)
btn1['text'] = ' Click on '
btn1.pack()
def test(e):
messagebox.showinfo(' Window name ', ' Click success ')
btn1.bind('<Button-1>', test)
root.mainloop()
3 Layout manager , pack
, grid
and place
.
pack
Or arrange the components vertically , Or arrange them horizontally grid
grid
( grid ) The layout manager places the controls in a two-dimensional table . The main control is divided into a series of rows and columns , Each cell in the table (cell
) Can place a control .grid_info()
You can view the default parameters of the component .{'in': <tkinter.Tk object .>, 'column': 0, 'row': 0, 'columnspan': 1, 'rowspan': 1, 'ipadx': 0, 'ipady': 0, 'padx': 0, 'pady': 0, 'sticky': ''}
grid Manager
column
The column number of the cell , from 0 A positive integer at the beginning columnspan
Cross column , The number of columns crossed , Positive integer row
The line number of the cell , from 0 A positive integer at the beginning rowspan
enjambment , The number of lines crossed , Positive integer ipadx, ipady
Set the spacing between subcomponents ,x Direction or y Direction , The default unit is pixels , Non floating point number , Default 0.0padx, pady
The space between the components juxtaposed with it ,x Direction or y Direction , The default unit is pixels , Non floating point number , Default 0.0sticky
Component clings to a foot of the cell where it is located , Corresponding to Southeast, northwest, middle and 4 Corner . In the east = “e”, south =“s”, In the west =“w”, north =“n”,“ne”,“se”,“sw”, “nw”column
Specify the column where the control is located import tkinter as tk
root = tk.Tk()
root.title(' Window title ')
root.geometry("300x100+630+80")
btn1 = tk.Button(root)
btn1['text'] = ' Click on '
btn1.grid(column=1)
btn2 = tk.Button(root)
btn2['text'] = ' sign out '
btn2.grid(column=3)
root.mainloop()
padx
Horizontal outer margin import tkinter as tk
root = tk.Tk()
root.title(' Window title ')
root.geometry("300x100+630+80")
btn1 = tk.Button(root)
btn1['text'] = ' Click on '
btn1.grid(column=3, padx=20)
btn2 = tk.Button(root)
btn2['text'] = ' sign out '
btn2.grid(column=1, padx=20)
btn3 = tk.Button(root)
btn3['text'] = ' Cancel '
btn3.grid(column=2, padx=20)
root.mainloop()
pady
Vertical outer margin import tkinter as tk
root = tk.Tk()
root.title(' Window title ')
root.geometry("300x100+630+80")
btn1 = tk.Button(root)
btn1['text'] = ' Click on '
btn1.grid(column=3, pady=20)
btn2 = tk.Button(root)
btn2['text'] = ' sign out '
btn2.grid(column=1, pady=20)
btn3 = tk.Button(root)
btn3['text'] = ' Cancel '
btn3.grid(column=2, pady=20)
root.mainloop()
sticky
Component southeast northwest direction import tkinter as tk
root = tk.Tk()
root.title(' Window title ')
root.geometry("300x100+630+80")
btn1 = tk.Button(root)
btn1['text'] = ' Click on '
btn1.grid(column=3, sticky='w')
btn2 = tk.Button(root)
btn2['text'] = ' sign out '
btn2.grid(column=1, sticky='e')
btn3 = tk.Button(root)
btn3['text'] = ' Cancel '
btn3.grid(column=2, sticky='s')
root.mainloop()
row
Specify the row where the control is located import tkinter as tk
root = tk.Tk()
root.title(' Window title ')
root.geometry("300x100+630+80")
btn1 = tk.Button(root)
btn1['text'] = ' Click on '
btn1.grid(row=3)
btn2 = tk.Button(root)
btn2['text'] = ' sign out '
btn2.grid(row=1)
btn3 = tk.Button(root)
btn3['text'] = ' Cancel '
btn3.grid(row=2)
root.mainloop()
ipadx
Horizontal inner margin import tkinter as tk
root = tk.Tk()
root.title(' Window title ')
root.geometry("300x100+630+80")
btn1 = tk.Button(root)
btn1['text'] = ' Click on '
btn1.grid(row=3, ipadx=5)
btn2 = tk.Button(root)
btn2['text'] = ' sign out '
btn2.grid(row=1, ipadx=20)
btn3 = tk.Button(root)
btn3['text'] = ' Cancel '
btn3.grid(row=2, ipadx=10)
root.mainloop()
ipady
Vertical inner margin import tkinter as tk
root = tk.Tk()
root.title(' Window title ')
root.geometry("300x100+630+80")
btn1 = tk.Button(root)
btn1['text'] = ' Click on '
btn1.grid(row=3, ipady=5)
btn2 = tk.Button(root)
btn2['text'] = ' sign out '
btn2.grid(row=1, ipady=20)
btn3 = tk.Button(root)
btn3['text'] = ' Cancel '
btn3.grid(row=2, ipady=10)
root.mainloop()
place Manager place
The layout manager can precisely control the position of components through coordinates , It is suitable for some scenes with more flexible layout .
x
, y
Absolute coordinates of the upper left corner of the component ( Equivalent to window )relx
,rely
Coordinates of the upper left corner of the component ( Relative to the parent container )width
, height
Width and height of components relwidth
, relheight
Width and height of components ( Relative to the parent container )anchor
Alignment mode , Align left w
, Right alignment e
, Top alignment n
, Bottom alignment s
import tkinter as tk
root = tk.Tk()
root.title(' Window title ')
root.geometry("300x100+630+80")
btn1 = tk.Button(root)
btn1['text'] = ' Click on '
btn1.place(relx=0.2, x=10, y=20, relwidth=0.2, relheight=0.5)
btn2 = tk.Button(root)
btn2['text'] = ' sign out '
btn2.place(relx=0.2, x=70, y=20, relwidth=0.2, relheight=0.5)
btn3 = tk.Button(root)
btn3['text'] = ' Cancel '
btn3.place(relx=0.2, x=130, y=20, relwidth=0.2, relheight=0.5)
root.mainloop()
import tkinter as tk
from tkinter import ttk - Drop down the selection box
class GUI:
def __init__(self):
self.root = tk.Tk()
self.root.title(' Window title ')
self.root.geometry("300x100+630+80")
self.interface()
def interface(self):
"""" Interface writing location """
pass
if __name__ == '__main__':
gui = GUI()
gui.root.mainloop()
?
def interface(self):
"""" Interface writing location """
self.Label0 = tk.Label(self.root, text=" Text display ")
self.Label0.grid(row=0, column=0)
def interface(self):
"""" Interface writing location """
self.Button0 = tk.Button(self.root, text=" Button display ")
self.Button0.grid(row=0, column=0)
def interface(self):
"""" Interface writing location """
self.Entry0 = tk.Entry(self.root)
self.Entry0.grid(row=0, column=0)
pack
Layout def interface(self):
"""" Interface writing location """
self.w1 = tk.Text(self.root, width=80, height=10)
self.w1.pack(pady=0, padx=30)
grid
Layout def interface(self):
"""" Interface writing location """
self.w1 = tk.Text(self.root, width=80, height=10)
self.w1.grid(row=1, column=0)
def interface(self):
"""" Interface writing location """
self.Checkbutton01 = tk.Checkbutton(self.root, text=" name ")
self.Checkbutton01.grid(row=0, column=2)
def interface(self):
"""" Interface writing location """
self.Radiobutton01 = tk.Radiobutton(self.root, text=" name ")
self.Radiobutton01.grid(row=0, column=2)
def interface(self):
"""" Interface writing location """
values = ['1', '2', '3', '4']
self.combobox = ttk.Combobox(
master=self.root, # Parent container
height=10, # Height , The number of items displayed in the drop-down
width=20, # Width
state='', # Set the state of normal( Optional, you can enter )、readonly( Optional only )、 disabled( Disable input selection )
cursor='arrow', # Style when the mouse moves arrow, circle, cross, plus...
font=('', 15), # typeface 、 Font size
textvariable='', # adopt StringVar Set changeable values
values=values, # Set the options of the drop-down box
)
self.combobox.grid(padx=150)
def interface(self):
"""" Interface writing location """
self.Button0 = tk.Button(self.root, text=" function ", command=self.event)
self.Button0.grid(row=0, column=0)
self.Button1 = tk.Button(self.root, text=" sign out ", command=self.root.destroy, bg="Gray") # bg= Color
self.Button1.grid(row=0, column=1, sticky="e", ipadx=10)
def event(self):
""" Button event """
print(" The successful running ")
return ' The button event is over !'
def interface(self):
"""" Interface writing location """
self.entry00 = tk.StringVar()
self.entry00.set(" Default message ")
self.entry0 = tk.Entry(self.root, textvariable=self.entry00)
self.entry0.grid(row=0, column=0)
self.Button0 = tk.Button(self.root, text=" function ", command=self.event)
self.Button0.grid(row=1, column=0)
def event(self):
""" Button event , Get text information """
global entry
entry = self.entry00.get()
For obtaining the contents of the input box 、 Cleared instances , Please refer to here 3.
def interface(self):
"""" Interface writing location """
self.w1 = tk.Text(self.root, width=20, height=3)
self.w1.grid(row=0, column=0)
self.w1.insert("insert", " Default message ")
self.Button0 = tk.Button(self.root, text=" eliminate ", command=self.event)
self.Button0.grid(row=1, column=0)
def event(self):
""" Clear the input box """
self.w1.delete(0.0, "end")
def interface(self):
"""" Interface writing location """
self.v1 = tk.IntVar()
self.Checkbutton01 = tk.Checkbutton(self.root, text=" Check box ", command=self.Check_box, variable=self.v1)
self.Checkbutton01.grid(row=0, column=0)
self.w1 = tk.Text(self.root, width=20, height=10)
self.w1.grid(row=1, column=0)
self.Button0 = tk.Button(self.root, text=" determine ", command=self.event)
self.Button0.grid(row=2, column=0)
def event(self):
''' Button event , Gets the status of the check box ,1 Indicates that... Is checked ,0 Indicates not checked '''
a = self.v1.get()
self.w1.insert(1.0, str(a) + '\n')
def Check_box(self):
''' Check box events '''
if self.v1.get() == 1:
self.w1.insert(1.0, " Check " + '\n')
else:
self.w1.insert(1.0, " Uncheck " + '\n')
def interface(self):
"""" Interface writing location """
self.Label0 = tk.Label(self.root, text=" Text display ")
self.Label0.grid(row=0, column=0)
self.Entry0 = tk.Entry(self.root)
self.Entry0.grid(row=1, column=0)
self.w1 = tk.Text(self.root, width=20, height=2)
self.w1.grid(row=2, column=0)
self.Button0 = tk.Button(self.root, text=" determine ", command=self.event)
self.Button0.grid(row=3, column=0)
def event(self):
''' Button event , eliminate Label、Entry、Text Components '''
a = [self.Label0, self.Entry0, self.w1]
for i in a:
i.grid_forget()
def interface(self):
"""" Interface writing location """
self.v1 = tk.IntVar()
self.Checkbutton01 = tk.Checkbutton(self.root, text=" Check box ", command=self.Check_box, variable=self.v1)
self.Checkbutton01.grid(row=0, column=0)
self.w1 = tk.Text(self.root, width=20, height=2)
self.w1.grid(row=1, column=0)
self.Button0 = tk.Button(self.root, text=" eliminate ", command=self.event)
self.Button0.grid(row=2, column=0)
def event(self):
''' Button event , Clear the check box to check the status '''
self.Checkbutton01.deselect()
def Check_box(self):
''' Check box events '''
if self.v1.get() == 1:
self.w1.insert(1.0, " Check " + '\n')
else:
self.w1.insert(1.0, " Uncheck " + '\n')
def interface(self):
"""" Interface writing location """
self.w1 = tk.Text(self.root, width=20, height=2)
self.w1.grid(row=0, column=0)
self.Button0 = tk.Button(self.root, text=" determine ", command=self.event)
self.Button0.grid(row=1, column=0)
def event(self):
''' Button event , Get text box content '''
a = self.w1.get('0.0', 'end')
print(a)
About how to make 1 individual Tkinter
Enter the field and close it , Please refer to here 4.
def interface(self):
"""" Interface writing location """
self.value = tk.StringVar()
self.value.set('2') # The default value is
values = ['1', '2', '3', '4']
self.combobox = ttk.Combobox(
master=self.root, # Parent container
height=10, # Height , The number of items displayed in the drop-down
width=20, # Width
state='', # Set the state of normal( Optional, you can enter )、readonly( Optional only )、 disabled( Disable input selection )
cursor='arrow', # Style when the mouse moves arrow, circle, cross, plus...
font=('', 15), # typeface
textvariable=self.value, # adopt StringVar Set changeable values
values=values, # Set the options of the drop-down box
)
self.combobox.bind("<<ComboboxSelected>>", self.pick) # The binding event , When the drop-down list box is selected , binding pick() function
self.combobox.grid(padx=20)
def pick(self, *args): # Handling events ,*args Represents a variable parameter
print(' Selected data :{} \n value Value :{}'.format(self.combobox.get(), self.value.get()))
For the instance of the drop-down box binding event , Please refer to here 5.
%todo
%todo
%todo:
python And Tkinter The use of, ︎
TkDocs︎
Python And tkinter The text box Entry The basic application of ︎
How to make a tkinter Enter the field and close it ︎
tkinter Examples of module usage – The window closes after user input ︎