You can't write interface software in Python! Which software on sale has no UI?

Python Programming 2021-09-15 09:25:36
write interface software python software


tkinter Introduce

tkinter yes python Self contained GUI library , It's about the graphics library TK Encapsulation
tkinter It's a cross platform GUI library , The developed program can be win,linux perhaps mac Run under

Component concept

Any content in a window can be called a component

tkinter The components of include the following

 Of course, I'm learning Python It's going to be difficult , There is no good learning material , How to learn ?
 Study Python I don't know how to recommend to join the communication Q Group number :928946953
There are like-minded partners in the group , Help each other , There are good video tutorials and PDF!
And Daniel's answer !

 

Button components

  Copy code  Hidden code Button  Button components RadioButton  Radio box components CheckButton  Select the button component Listbox  Listbox components 

Text input box component

  Copy code  Hidden code Entry  Single line text box component Text  Multiline text box component 

Tag components

  Copy code  Hidden code Label  Tag components , It can show pictures and words Message  Tag components , You can wrap the text according to the content 

Menu components

  Copy code  Hidden code Menu  Menu components MenuButton  Menu button components , have access to Menu Instead of 

Scroll bar assembly

  Copy code  Hidden code scale  Slider as Scrollbar  Scroll bar assembly 

Other components

  Copy code  Hidden code Canvas  Canvas components Frame  Frame components , Group multiple components Toplevel  Create a child window container component 

create a window

Simple window

 Copy code Hidden code
import tkinter # Create a main window win = tkinter.Tk() # Set title win.title("Python-14") # Set window size and position # 500x500 Represents the size of the window # +200+50 Indicates the distance between the window and the left and top edges of the computer screen win.geometry("500x500+200+50") # Start main window win.mainloop()

Windows with components

  Copy code  Hidden code import tkinter # Generate the main window object root = tkinter.Tk() # Create a label And add it to the main window label = tkinter.Label(root,text = ' Here comes the Lord ') label.pack() # Create button , And add it to the main window btn1 = tkinter.Button(root,text = ' Button 1') btn1.pack() btn2 = tkinter.Button(root,text = ' Button 2') btn2.pack() # Keep the main window in the message loop .. root.mainloop()

Component layout

There are three ways of component layout

 Copy code Hidden code
pack() Layout by orientation place() Layout according to coordinates grid() According to the grid layout 

1.pack Layout method

be-all Tkinter Components contain dedicated geometry management methods , These methods are used to organize and manage the layout of sub accessories in the whole parent accessories area .Tkinter Three distinct geometry management classes are provided :pack、grid and place.
pack Geometry management organizes accessories in a block manner , It is widely used in rapid generation interface design , Simple layout of several components , use pack The least amount of code .pack Geometry management procedure according to In the order of component creation and generation, add components to the parent component . By setting the same anchor (anchor) A set of accessories can be placed next to one place , If you don't specify any options , Add components from top to bottom in the parent form by default .

pack() General formula for layout

 Copy code Hidden code
Component object .pack( Set up , …) 
 

name

describe

Value range

expand

The duty of “yes” when ,side Invalid option . The component is displayed in the center of the parent fitting ; if fill The options are ”both”, Then fill in the remaining space of the parent component .

“yes”, Natural number , “no”, 0( The default value is “no” or 0)

fill

fill x(y) Space in direction , When the attribute side=”top” or ”bottom” when , fill x Direction ; When the attribute side=”left” or ”right” when , fill ”y” Direction ; When expand The options are ”yes” when , Fill the remaining space of the parent component .

“x”, “y”, “both”( The default value is to be selected )

ipadx, ipady

Inside the component is x(y) The size of the space filled in the direction , The default unit is pixels , The optional units are c( centimeter )、m( mm )、i( Inch )、p( Printer point , namely 1/27 Inch ), The usage is to add the above suffix after the value to .

Nonnegative floating point number ( The default value is 0.0)

padx, pady

Outside the component is x(y) The size of the space filled in the direction , The default unit is pixels , The optional units are c( centimeter )、m( mm )、i( Inch )、p( Printer point , namely 1/27 Inch ), The usage is to add the above suffix after the value to .

Nonnegative floating point number ( The default value is 0.0)

side

Define which side of the parent component to dock on .

“top”, “bottom”, “left”, “right”( The default is ”top”)

before

Apply this component before the selected build object pack, This is similar to creating this component before creating the selected component .

already pack Component object after

after

Apply this component after the selected build object pack, This is similar to creating the selected component first and then this component .

already pack Component object after

in_

Make this component a child of the selected build object , Similar to specifying the of this component master For the selected component .

already pack Component object after

anchor

Alignment relative to the position where the components are placed , Align left ”w”, Right alignment ”e”, Top alignment ”n”, Bottom alignment ”s”

“n”, “s”, “w”, “e”, “nw”, “sw”, “se”, “ne”, “center”( The default is ” center”)

 
 
 

notes : As can be seen from the above options expand、fill and side It's interactive .

pack Class provides the following functions

 

Function name

describe

slaves()

Return all sub component objects of this component in list mode .

propagate(boolean)

Set to True Indicates that the geometry size of the parent component is determined by the child component ( The default value is ), Otherwise, it has nothing to do with it .

info()

return pack Value corresponding to the provided option .

forget()

Unpack Components , Hide components and ignore old settings , Object still exists , It can be used pack(option, …), Display it .

location(x, y)

x, y Is a point in pixels , Function returns whether the point is in a cell , In which cell . Return cell row and column coordinates ,(-1, -1) Means not in it .

size()

Return the cells contained in the component , Reveal component size .

 
 
 

2.grid Layout method

grid Geometry management is organized in a table like structure , Very flexible to use , It works best to design dialog boxes and forms with scroll bars .grid Mining Determine the position with rows and columns , The intersection of rows and columns is a cell . In each column , Column width is determined by the widest cell in this column . In every line , The row height is determined by the highest cell in the row . Components don't fill the whole list Metalattice , You can specify the use of the remaining space in the cell . You can free up these spaces , These spaces can also be filled horizontally or vertically or in both directions . You can connect several cells into a larger space , This operation is called crossing . The created cell must be adjacent to .

grid() The general formula for layout is

 Copy code Hidden code
Component object .grid(option, …)

grid Class provides the following settings properties

 

name

describe

Value range

column

The column number of the cell set by the component .

Natural number ( The starting default value is 0, Then add up )

columnspan

The span in the column direction from the cell where the component is placed .

Natural number ( The starting default value is 0)

ipadx, ipady

Inside the component is x(y) The size of the space filled in the direction , The default unit is pixels , The optional units are c( centimeter )、m( mm )、i( Inch )、p( Printer point , namely 1/27 Inch ), The usage is to add the above suffix after the value to .

Nonnegative floating point number ( The default value is 0.0)

padx, pady

Outside the component is x(y) The size of the space filled in the direction , The default unit is pixels , The optional units are c( centimeter )、m( mm )、i( Inch )、p( Printer point , namely 1/27 Inch ), The usage is to add the above suffix after the value to .

Nonnegative floating point number ( The default value is 0.0)

row

The row number of the cell set by the component .

Natural number ( The starting default value is 0, Then add up )

rowspan

The span in the row direction from the cell where the component is placed .

Natural number ( The starting default value is 0)

in_

Make this component a child of the selected build object , Similar to specifying the of this component master For the selected component .

already pack Component object after

sticky

The component is close to one corner of the cell .

“n”, “s”, “w”, “e”, “nw”, “sw”, “se”, “ne”, “center”( The default is ” center”)

 
 
 

grid Class provides the following functions

 

Function name

describe

slaves()

Return all sub component objects of this component in list mode .

propagate(boolean)

Set to True Indicates that the geometry size of the parent component is determined by the child component ( The default value is ), Otherwise, it has nothing to do with it .

info()

return pack Value corresponding to the provided option .

forget()

Unpack Components , Hide components and ignore old settings , Object still exists , It can be used pack(option, …), Display it .

grid_remove()

Remove this widget from the grid manager . Widgets will not be destroyed , And can be redisplayed by the grid or any other manager .

 
 
 

3.place Layout method

This geometry manager organization is placed in a specific location , In their father widget parts .

place() The general formula for layout is :

 Copy code Hidden code
Component object .place(option, …)
 

name

describe

Value range

anchor

Position relative to the coordinates where the components are placed

see also : May be N,E,S,W, The northeast , The northwest , Southeast or southwest , Compass direction indication widget The corner of , Both parties default to the net weight ( Upper left corner of part )

height

Height in pixels .( Absolute layout specific )

Pixels

width

Width in pixels .( Absolute layout specific )

Pixels

relheight

The height of the component relative to the window ( Relative layout specific )

0~1

relwidth

The width of the component relative to the window ( Relative layout specific )

0~1

relx

The horizontal offset is 0.0 and 1.0 Between the floating , Father widget The height and width of a small part of .( Relative layout specific )

0~1

rely

The vertical offset is 0.0 and 1.0 Between the floating , Father widget The height and width of a small part of .( Relative layout specific )

0~1

x

The component is located at the top left corner x coordinate ( Absolute layout specific )

Pixels

y

The component is located at the top left corner y coordinate ( Absolute layout specific )

Pixels

 
 
 

place Class provides the following functions ( Call with component instance object )

 

Function name

describe

place_slaves()

Return all sub component objects of this component in list mode .

place_configure(option=value)

to pack Layout manager settings properties , Use attributes (option)= Value (value) Mode setting

propagate(boolean)

Set to True Indicates that the geometry size of the parent component is determined by the child component ( The default value is ), Otherwise, it has nothing to do with it .

place_info()

return pack Value corresponding to the provided option .

grid_forget()

Unpack Components , Hide components and ignore old settings , Object still exists , It can be used pack(option, …), Display it .

location(x, y)

x, y Is a point in pixels , Function returns whether the point is in a cell , In which cell . Return cell row and column coordinates ,(-1, -1) Means not in it

size()

Return the cells contained in the component , Reveal component size .

 
 
 

Component is introduced

Components 1 Button (button)

Used for definition GUI Button components in the interface

 Copy code Hidden code
tkinter.Button( Parent component for storage , Property parameters ...)

Have the following properties

  Copy code  Hidden code anchor  Set the alignment of the text in the button , Relative to the center of the button background(bg)  Set the background color of the button foreground(fg)  Set the foreground color of the button ( Color of text ) borderwidth(bd)  Set the button border width cursor  Set the style of the mouse on the button command  Set the function triggered when the button is clicked bitmap  Set the bitmap displayed on the button font  Set the font of the text on the button width  Set the width of the button ( The number of characters ) height  Set the height of the button ( The number of characters ) state  Set the state of the button text  Set the text on the button image  Set the picture on the button 
  Copy code  Hidden code import tkinter # Create a main window win = tkinter.Tk() # Set title win.title("Python-14") # Set window size and position # 500x500 Represents the size of the window # +200+50 Indicates the distance between the window and the left and top edges of the computer screen win.geometry("500x500+200+50") button1 = tkinter.Button(win, text = " sign out ", width = 20, height = 5, command = win.quit ) button1.pack() def func(): print(" welcome !") button2 = tkinter.Button(win, text = " I have a surprise ", width = 30, height = 20, command = func ) button2.pack() # Start main window win.mainloop()

Components 2 The text box (Entry) And multiline text (Text)

Single line input box used to define the text in the page

 Copy code Hidden code
# Single line text tkinter.Entry( Parent component for storage , Property parameters ...) # Multiline text tkinter.Text( Parent component for storage , Property parameters ...)

Have the following properties

  Copy code  Hidden code background(bg)  Set the background color of the text box foreground(fg)  Set the foreground color of the text box borderwidth(bd)  Set the border of the text input box font  Set the font in the text box width  Set the width of the text box ( The number of characters ) height  Set the height of the text box ( The number of characters ), Is limited to text state  Set the status of the text box selectbackground  The background color of the text box when text is selected selectforeground  The color of the text when the text is selected show  Specifies the characters displayed in the text box , if *, It is represented as password box textvariable  Set the variable corresponding to the text , You can change the text display by modifying variables . You have to use tkinter.IntVar() or tkinter.StringVar() Generated variables entry have access to 
 Copy code Hidden code
import tkinter # Create a main window win = tkinter.Tk() # Set title win.title("Python-14") # Set window size and position win.geometry("500x500+250+150") # Set a variable , Used to receive the contents of the input control e1 = tkinter.Variable() # Input box control # show Hide the input entry = tkinter.Entry(win,textvariable = e1,show = "@") entry.pack() # Set the default content in the input box e1.set(" Please enter a user name ") print(e1.get()) # Set button submit def func(): print(e1.get()) button = tkinter.Button(win,text = " Submit ",command = func) button.pack() # Start main window win.mainloop()
 Copy code Hidden code
import tkinter win = tkinter.Tk() win.title("Python-14") win.geometry("500x500+200+100") # Create a scroll bar scroll = tkinter.Scrollbar() text = tkinter.Text(win,width = 100,height = 40) # Displays the scroll bar position Put it on the right side fill Y Axis scroll.pack(side = tkinter.RIGHT,fill = tkinter.Y) # Display of text box text.pack(side = tkinter.LEFT,fill = tkinter.Y) # Bind scroll bar and text box scroll.config(command = text.yview) # Bind text box and scroll bar text.config(yscrollcommand = scroll.set) str = """ Christmas Day is on December 25th. It was originated in the western country, but today, this festival has been celebrated by the world. For the manufacturers, they are very happy to make this day as a shopping day. I enjoy the great atmosphere. I had a very special Christmas day last year. I experienced the western style festival. There was a new foreign teacher taught us the lesson. She was about 50 years old and she was very kind and we all liked her. On Christmas Day, she brought us the desserts she made early in the morning. We enjoyed the home-made cakes. What's more, she invited us to came to her house and spent the day with her. Then for the first time, I ate big turkey, which was so delicious. The turkey was filled with many stuffs and the flavor was so good. After dinner, we sang songs and danced. Thanks to my foreign teacher, I experienced the American style festival. It was such funny for me. Though today many people enjoy shopping in all kinds of festivals, the meaning of these festival should be remembered. Christmas Day is on December 25th. It was originated in the western country, but today, this festival has been celebrated by the world. For the manufacturers, they are very happy to make this day as a shopping day. I enjoy the great atmosphere. """ text.insert(tkinter.INSERT,str) win.mainloop()
 Copy code Hidden code
import tkinter win = tkinter.Tk() win.title("Python-14") win.geometry("500x500+200+100") # Create an input box entry = tkinter.Entry(win) entry.pack() # Create a text box text = tkinter.Text(win,width = 50,height = 20) text.pack() # Write a function to read the file def func(): with open(entry.get(),"r") as f: content = f.read() text.insert(tkinter.INSERT,content) # Write a function to save the contents of the file def func1(): with open(entry.get(),"w") as f: # The content written is In the text box, select from 0 That's ok 0 Column to end f.write(text.get(0.0,tkinter.END)) # Create two buttons button1 = tkinter.Button(win,text = " preservation ",command = func1) button2 = tkinter.Button(win,text = " Read ",command = func) button1.pack() button2.pack() win.mainloop()

Components 3 label (Lebal)

Label terms display text or pictures in the page

 Copy code Hidden code
tkinter.Label( Parent component for storage , Property parameters ...)

Have the following properties

  Copy code  Hidden code anchor  Sets the position of the text relative to the center of the label background(bg)  Set the background color of the label foreground(fg)  Set the foreground color of the label borderwidth(bd)  Set the border width of the label width  Set the width of the label ( The number of characters ) height  Set the height of the label ( The number of characters ) text  Set the text content in the label font  Set the font type of the text in the label bitmap  Sets the realistic bitmap of the label image  Set the picture displayed in the label justify  Set the alignment of multiline text in the label textvariable  Set the variable corresponding to the text , You can change the text display by modifying variables , You have to use tkinter.IntVar() perhaps tkinter.StringVar() Generated variables 
  Copy code  Hidden code import tkinter # Create a main window win = tkinter.Tk()  # Set title win.title("Python-14")  # Set window size and position # 500x500 Represents the size of the window # +200+50 Indicates the distance between the window and the left and top edges of the computer screen win.geometry("500x500+200+50") """ Label: Tag space , Can display text win: main window text: Show text content bg: The background color fg: The font color font: Set font and font size wraplength: Appoint text Wrap after medium width anchor: Position of text display n north e In the east s south w In the west center In the middle ne se sw nw justify: Set the alignment after line feed """ label = tkinter.Label(win, text = "this is a python test", bg = "red", fg = "yellow", font = (" In black ",26), width = 5, height = 10, wraplength = 100, anchor = "n", justify = "right" ) # Show labels label.pack() # Start main window win.mainloop()

Components 4 Radio buttons (Radiobutton) With checkboxes (Checkbutton)

 Copy code Hidden code
thinter.Radiobutton( Parent component for storage , Property parameters ...) thinter.Checkbutton( Parent component for storage , Property parameters ...)

Has the following properties

  Copy code  Hidden code anchor  Set the alignment of the text in the component background(bg)  Specifies the background color of the component . borderwidth(bd)  Specifies the width of the component border . bitmap  Specifies the bitmap in the component . font  Specifies the font of the text in the component . foreground(fg)  Specifies the front of the component height  Specify the height of the component . image  Specify the picture in the component . justify  Specifies the alignment of multiline text in the component . text  Specifies the text in the component , Sure Use “\ n” Means line break . value  Specify the value of the status after the component is selected ( Radio buttons ) onvalue  Check the status value of the component ( Check box ) offvalue  The value of the unchecked status of the component ( Check box ) variable  Specifies the variables associated with the component . Need to use tkinter. IntVar() perhaps tkinter. StringVar() Created value width  Specifies the width of the component . command  Set the trigger command for the check box operation ( Check box )
 Copy code Hidden code
# Check box import tkinter win = tkinter.Tk() win.title("Python-14") win.geometry("500x500+200+100") def func(): message = "" if res1.get(): message += " Zhang San \n" if res2.get(): message += " Li Si \n" if res3.get(): message += " Wang Wu \n" # eliminate text Everything in text.delete(0.0,tkinter.END) # hold message write in text in text.insert(tkinter.INSERT,message) # Determine whether the check box is selected Return to one bool value res1 = tkinter.BooleanVar() # Create a check box check1 = tkinter.Checkbutton(win,text = " Zhang San ",variable = res1) check1.pack() res2 = tkinter.BooleanVar() check2 = tkinter.Checkbutton(win,text = " Li Si ",variable = res2) check2.pack() res3 = tkinter.BooleanVar() check3 = tkinter.Checkbutton(win,text = " Wang Wu ",variable = res3) check3.pack() # Create a text box text = tkinter.Text(win,width = 50,height = 20) text.pack() # Create a button button = tkinter.Button(win,text = "submit",width = 10,height = 5,command = func) button.pack() win.mainloop()
  Copy code  Hidden code # Radio buttons import tkinter win = tkinter.Tk() win.title("Python-14") win.geometry("500x500+200+100")  # Gets the name of the radio box value res = tkinter.StringVar() # Define a function To print the of the radio box value value def func(): print(res.get())  # Create a menu radio1 = tkinter.Radiobutton( win, text = " Zhang San ", value = 1, variable = res, command = func ) radio2 = tkinter.Radiobutton( win, text = " Li Si ", value = 2, variable = res, command = func ) radio3 = tkinter.Radiobutton( win,text = " Wang Wu ", value = 3, variable = res, command = func ) # Show radio boxes radio1.pack() radio2.pack() radio3.pack() win.mainloop()

Components 5 Frame frame

 Copy code Hidden code
thinter.Menu( Parent component for storage , Property parameters ...)

Has the following properties

  Copy code  Hidden code background(bg)  Normal background colors are displayed behind labels and indicators . borderwidth(bd)  The size of the boundary around the indicator . The default value is 2 Pixels . cursor  If this option is set to cursor name ( arrow , Point etc ), The mouse cursor will change to this mode above the check button . height  Vertical dimensions of the new frame . highlightbackground  When the frame has no focus , The color of the focus highlights . highlightcolor  When the frame has focus , Focus highlight color . highlightthickness  The thickness of the focal spot . relief  Use the default value ,relief = FLAT, The check button does not stand out from the background . You can set this option to any other style width checkbutton The default width of depends on the size of the displayed image or text . You can set the number of characters and checkbutton Of , There is always room for many characters .
 Copy code Hidden code
# Layout import tkinter win = tkinter.Tk() win.title("Pyhton-14") win.geometry("500x500+200+100") # Create a framework frame = tkinter.Frame(win) frame.pack() # On the left frm1 = tkinter.Frame(frame) lable1 = tkinter.Label(frm1,text = " Top left ",bg = "red",width = 10,height = 5) lable2 = tkinter.Label(frm1,text = " The lower left ",bg = "yellow",width = 10,height = 5) lable1.pack(side = tkinter.TOP) lable2.pack(side = tkinter.TOP) frm1.pack(side = tkinter.LEFT) # On the right frm2 = tkinter.Frame(frame) lable3 = tkinter.Label(frm2,text = " The upper right ",bg = "green",width = 10,height = 5) lable4 = tkinter.Label(frm2,text = " The lower right ",bg = "blue",width = 10,height = 5) lable3.pack(side = tkinter.TOP) lable4.pack(side = tkinter.TOP) frm2.pack(side = tkinter.RIGHT) win.mainloop()
  Copy code  Hidden code # Absolute positioning import tkinter win = tkinter.Tk() win.geometry("500x500+200+100") lable1 = tkinter.Label(win,text = " Xiaohong ",bg = "red",width = 20,height = 10) lable2 = tkinter.Label(win,text = " Xiao Ming ",bg = "green",width = 20,height = 10) lable3 = tkinter.Label(win,text = " Li lei ",bg = "yellow",width = 20,height = 10) lable1.place(x = 0,y = 0) lable2.place(x = 370,y = 0) lable3.place(x = 0,y = 310) win.mainloop()
 Copy code Hidden code
# Relative positioning import tkinter win = tkinter.Tk() win.title("Python-14") win.geometry("500x500+200+100") label1 = tkinter.Label(win,text = " Xiaohong ",bg = "red") label2 = tkinter.Label(win,text = " Xiao Ming ",bg = "green") label3 = tkinter.Label(win,text = " Li lei ",bg = "yellow") label1.pack(fill = tkinter.Y,side = tkinter.LEFT) label2.pack(fill = tkinter.Y,side = tkinter.RIGHT) label3.pack(fill = tkinter.X,side = tkinter.TOP) label3.pack() win.mainloop()
 Copy code Hidden code
# Table layout import tkinter win = tkinter.Tk() win.title("Python-14") win.geometry("500x500+200+100") lable1 = tkinter.Label(win,text = " Xiaohong ",bg = "red") lable2 = tkinter.Label(win,text = " Xiao Huang ",bg = "yellow") lable3 = tkinter.Label(win,text = " Small blue ",bg = "blue") lable4 = tkinter.Label(win,text = " Small powder ",bg = "pink") # Table layout lable1.grid(row = 0,column = 0) lable2.grid(row = 0,column = 1) lable3.grid(row = 1,column = 0) lable4.grid(row = 1,column = 1) win.mainloop()

Event binding

Previously, only 2 A component , A button, a menu tab command attribute Set the function corresponding to the operation

Mouse event type

 Copy code Hidden code
<Button-1> Press the left mouse button <ButtonPress-1> <Button-2> Press the middle mouse button <ButtonPress-2> <Button-3> Pressed the right mouse button <ButtonPress-3> <Enter> The mouse enters the component area <Leave> Move the mouse away from the component area <ButtonRelease-1> Released the left mouse button <ButtonRelease-2> Released the middle mouse button <ButtonRelease-3> Released the right mouse button <B1-Moion> Press and hold the left mouse button to move <B2-Moion> Press and hold the middle mouse button to move <B3-Moion> Press and hold the right mouse button to move <Double-Button-1> Double click the left mouse button <Double-Button-2> Double click the middle mouse button <Double-Button-3> Double click the right mouse button <MouseWheel> Scroll the mouse wheel 

Keyboard event type

 Copy code Hidden code
<KeyPress> Indicates that any keyboard is pressed <KeyPress-A> Indicates pressing the keyboard A key A It can be set as other keys <Alt-KeyPress-A> It means to press at the same time Alt and A key A It can be set as other keys <Control-KeyPress-A> It means to press at the same time Ctrl and A key A It can be set as other keys <Shift-KeyPress-A> It means to press at the same time Shift and A key A It can be set as other keys <Double-KeyPress-A> Double click the keyboard A key A It can be set as other keys <Lock-KeyPress-A> Indicates that after uppercase is turned on, the keyboard A key A It can be set as other keys <Alt-Control-KeyPress-A> It means to press at the same time alt+Ctrl and A key A It can be set as other keys Be careful : Keyboard events except entry and text It is better to bind the events of other components to the main interface 

The information contained in the event object

  Copy code  Hidden code x,y  The coordinate value of the mouse relative to the component triggering the event when the event is currently triggered x_root,y_root  The coordinate value of the mouse relative to the screen when the event is currently triggered char  Gets the character corresponding to the key pressed during the current keyboard event keycode  Gets the corresponding value of the key pressed during the current keyboard event ascii code type  Get the type of event num  Get the type of mouse button 123 Left middle right widget  The component that triggered the event width/height  The size and size of the component after change configure() relevant 

Window and component related event types

  Copy code  Hidden code Activate  When the component changes from unavailable to available Aim at state Variable value of Deactivate  Triggered when a component changes from available to unavailable Configure  Triggered when the component size changes Destory  Triggered when the component is destroyed FocusIn  Triggered when the component acquires focus Aim at Entry and Text It works Map  Triggered when the component changes from hidden to displayed UnMap  Triggered when the component changes from displayed to hidden Perproty  Triggered when the window properties change 

Event binding function

Components .bind(' Event type ', Event function )

 Copy code Hidden code
# Bind an operation to a component 

Components .bind_class(' Component type ',' Event type ', Event function )

 Copy code Hidden code
# Bind an operation for a class of components # The component type is the name of the method that creates the component For example, button components :Button

Components .bind_all(' Event type ', Event function )

 Copy code Hidden code
# Bind one operation for all components ( All operations will be treated as operations on the main interface ) 
 Copy code Hidden code
import tkinter win = tkinter.Tk() win.title("Python-14") win.geometry("500x500+200+100") def func(event): print(event.x,event.y) button = tkinter.Button(win,text = " Button ",width = 50,height = 20) button.bind("<Triple-Button-1>",func) button.pack() win.mainloop()

practice

Document comparison

 Copy code Hidden code
import sys import difflib # sys.argv : Get external runtime commands Return a list # sys.argv : Get external runtime commands Return a list # print(sys.argv) # # file1 = sys.argv[1] # file2 = sys.argv[2] # print(file1) # print(file2) # difflib # Create a comparison object HtmlDiff() Generate a html file # Comparison content make_file()
 Copy code Hidden code
import sys
import difflib
# sys.argv : Get external runtime commands Return a list # sys.argv : Get external runtime commands Return a list # print(sys.argv) # difflib # Create a comparison object HtmlDiff() Generate a html file # Comparison content make_file() first_path = sys.argv[1] # Get the name of the first file to compare next_path = sys.argv[2] # Get the name of the second file to compare # Read two files separately with open(first_path,"r") as f: first_list = f.readlines() with open(next_path,"r") as f: next_list = f.readlines() # Generate comparison object diff = difflib.HtmlDiff() html = diff.make_file(first_list,next_list) with open("diff.html","w") as f: f.write(html)
 Copy code Hidden code
# win+R cmd cd To the current address of the file # python file name .py file 1 file 2

Calculator

 Copy code Hidden code
from tkinter import * root = Tk() root.geometry('250x380') root.title(' Calculator ') frame_show = Frame(width=300,height=150,bg='#dddddd') # Top area v = StringVar() v.set('0') show_label = Label(frame_show,textvariable =v, bg = 'white',width=12,height=1,font=(" In black ", 20, "bold"),justify=LEFT,anchor='e') show_label.pack(padx = 10,pady = 10) frame_show.pack() # Whether the operator... Is pressed isopear = False # Operation sequence calc = [] def change(num): global isopear if isopear == False: if v.get() == '0': v.set('') v.set(num) else: v.set(v.get()+num) else: v.set(num) isopear = False # operation def operation(sign): global isopear global calc isopear = True calc.append(v.get()) if sign == '+': calc.append('+') elif sign == '-': calc.append('-') elif sign == '*': calc.append('*') elif sign == '/': calc.append('/') print(calc) def equal(): global calc # Get the value of the current interface and prepare for operation calc.append(v.get()) print(calc) # Form an operation string calcstr = ''.join(calc) # Check whether the last bit is an operator , If yes, delete it if calcstr[-1] in '+-*/': calcstr = calcstr[0:-1] #print(calcstr) # Operation result = eval(calcstr) # Show results v.set(result) calc.clear() # Delete operation def delete(): if v.get() == '' or v.get() == '0': v.set('0') return else: num = len(v.get()) if num > 1: strnum = v.get() strnum = strnum[0:num-1] v.set(strnum) else: v.set('0') # Emptying operation def clear(): global calc calc = [] v.set('0') isopear = False # Positive and negative operation def fan(): strnum = v.get() if strnum[0] == '-': v.set(strnum[1:]) elif strnum[0] != '-' and strnum != '0' : v.set('-'+strnum) # Key area frame_bord = Frame(width=400,height=350,bg='#cccccc') button_del = Button(frame_bord,text = '←',width = 5,height =1,command = delete).grid(row = 0,column = 0) button_clear = Button(frame_bord,text = 'C',width = 5,height =1,command = clear).grid(row = 0,column = 1) button_fan = Button(frame_bord,text = '±',width = 5,height =1,command = fan).grid(row = 0,column = 2) button_ce = Button(frame_bord,text = 'CE',width = 5,height =1,command = clear).grid(row = 0,column = 3) button_1 = Button(frame_bord,text = '1',width = 5,height =2,command = lambda:change('1')).grid(row = 1,column = 0) button_2 = Button(frame_bord,text = '2',width = 5,height =2,command = lambda:change('2')).grid(row = 1,column = 1) button_3 = Button(frame_bord,text = '3',width = 5,height =2,command = lambda:change('3')).grid(row = 1,column = 2) button_jia = Button(frame_bord,text = '+',width = 5,height =2,command = lambda:operation('+')).grid(row = 1,column = 3) button_4 = Button(frame_bord,text = '4',width = 5,height =2,command = lambda:change('4')).grid(row = 2,column = 0) button_5 = Button(frame_bord,text = '5',width = 5,height =2,command = lambda:change('5')).grid(row = 2,column = 1) button_6 = Button(frame_bord,text = '6',width = 5,height =2,command = lambda:change('6')).grid(row = 2,column = 2) button_jian = Button(frame_bord,text = '-',width = 5,height =2,command = lambda:operation('-')).grid(row = 2,column = 3) button_7 = Button(frame_bord,text = '7',width = 5,height =2,command = lambda:change('7')).grid(row = 3,column = 0) button_8 = Button(frame_bord,text = '8',width = 5,height =2,command = lambda:change('8')).grid(row = 3,column = 1) button_9 = Button(frame_bord,text = '9',width = 5,height =2,command = lambda:change('9')).grid(row = 3,column = 2) button_cheng = Button(frame_bord,text = 'x',width = 5,height =2,command = lambda:operation('*')).grid(row = 3,column = 3) button_0 = Button(frame_bord,text = '0',width = 5,height =2,command = lambda:change('0')).grid(row = 4,column = 0) button_dian = Button(frame_bord,text = '.',width = 5,height =2,command = lambda:change('.')).grid(row = 4,column = 1) button_deng = Button(frame_bord,text = '=',width = 5,height =2,command = equal).grid(row = 4,column = 2) button_chu = Button(frame_bord,text = '/',width = 5,height =2,command = lambda:operation('/')).grid(row = 4,column = 3) frame_bord.pack(padx = 10,pady = 10) root.mainloop()


======================
The post is very long , It's bound to be used one day . The notes are compiled by myself and have been used . If there is any error, please feedback , thank you .

版权声明
本文为[Python Programming]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/09/20210909143823978j.html

  1. 面对小白的pandas命令手册+练习题【三万字详解】
  2. 面對小白的pandas命令手册+練習題【三萬字詳解】
  3. Face au Manuel de commande pandas de Xiaobai + question d'exercice [30 000 mots pour plus de détails]
  4. Interprétation des questions d'entrevue de base Python | 100 couches d'entrevue Python | couche 1
  5. Python data structure and algorithm (17) -- merge sort
  6. Les fonctions intégrées Python exécutent des blocs de code de fonction à travers des chaînes, et les mécanismes de réflexion comme Java sont assez puissants!
  7. Python笔记-uiautomator2截图点击,OpenCV找图
  8. Python文档阅读笔记-OpenCV中Template Matching
  9. Python笔记-利用OpenCV的matchTemplate屏幕找图并使用pyautogui点击
  10. Python筆記-利用OpenCV的matchTemplate屏幕找圖並使用pyautogui點擊
  11. Notes python - utilisez l'écran matchtemplate d'OpenCV pour trouver des images et cliquez sur
  12. Notes de lecture de documents python - Matching de modèles dans OpenCV
  13. Notes python - capture d'écran de l'automate 2 Cliquez pour ouvrir la vue
  14. python链接云服务器的mysql8
  15. python鏈接雲服務器的mysql8
  16. Mysql8 pour les serveurs Cloud liés Python
  17. Python资源大集合,要的话可以拿走!
  18. ️万字【Python基础】保姆式教学️,小白快速入门Python!
  19. ️萬字【Python基礎】保姆式教學️,小白快速入門Python!
  20. Wanzi [base Python] Baby - sitting Teaching, Little White Quick Start Python!
  21. Realizing the function of sending e-mail automatically with Python
  22. Smtpauthenticationerror in Python: solution
  23. 8 steps to teach you how to solve Sudoku in Python! (including source code)
  24. Python change la vie | identifier facilement des centaines de numéros de livraison
  25. Python change life | utilisation de modèles reconnus par ocr
  26. Bibliothèques Python utiles et intéressantes - - psutil
  27. 3. Traitement des données pandas
  28. 【Python编程基础】控制流之链式比较运算符
  29. MFC uses Python scripting language
  30. 【Python編程基礎】控制流之鏈式比較運算符
  31. 【 base de programmation python】 opérateur de comparaison de chaîne pour le flux de contrôle
  32. Python game development, pyGame module, python implementation of Xiaole games
  33. Mise en œuvre du Code de vérification unique (OTP) avec le cadre de repos Django
  34. Python - eval ()
  35. Python - Programmation orientée objet - _Rapport()
  36. Différence entre python - rep (), Str ()
  37. Python - Programmation orientée objet - _Appel()
  38. Python calling matlab script
  39. Python - Programmation orientée objet - _Nouveau() et mode Singleton
  40. Python - Programmation orientée objet - méthode magique (méthode de double soulignement)
  41. Python - Programmation orientée objet - pratique (6)
  42. Python - Programmation orientée objet - réflexion hasattr, GetAttr, GetAttr, delattr
  43. Python - Programmation orientée objet - _Dict
  44. Python - pydantic (2) Modèle imbriqué
  45. Non-ASCII character ‘\xe5‘ in file kf1.py on line 4, but no encoding declared; see http://python.or
  46. python笔记(一)
  47. Non - ASCII character 'xe5' in file kf1.py on Line 4, but no Encoding declared;Voirhttp://python.or
  48. Notes Python (1)
  49. Talk about how JMeter executes Python scripts concurrently
  50. In Beijing, you can't see the moon in the Mid Autumn Festival. Draw a blood red moon in Python
  51. Un des pandas crée un objet
  52. Machine learning | unitary regression model Python practical case
  53. Draw a "Lollipop chart" with Excel and python
  54. Python uses scikit learn to calculate TF-IDF
  55. Getting started with Python Basics_ 3 conditional statements and iterative loops
  56. Python dynamic properties and features
  57. 云计算开发:Python内置函数-min()函数详解
  58. [Python skill] how to speed up loop operation and numpy array operation
  59. 雲計算開發:Python內置函數-min()函數詳解
  60. Développement de l'informatique en nuage: explication détaillée de la fonction intégrée python - min ()