English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Preface
The practical course on the computer began,嗯,After the teacher came, he read through the PPT and then said: Start working......
Then, I embarked on the journey of Python's GUI, having never been exposed to Python's visual interface before (though it was not very wise to do so)
But now it feels quite convenient to write small tools, and the first library I found was Tkinter, so I started writing directly
Later, it was found that QT is quite good, so the next experiment will use QT. Then, regarding Tkinter (Python3.6)
Calculator source code ennn.....Some names are not standardized......
Firstly, the implementation of stack in Python is simulated through the use of a list
pop() out of the stack, append() into the stack
First, let's take a look at the commonly used core small component classes provided by Tkinter:
Small component class | Description |
---|---|
Button | Button |
Canvas | Structured graphics, used for drawing graphics, creating graphic editors, and implementing custom small component classes |
Checkbutton | Click the checkbox to toggle between values |
Entry | Text field or text box |
Frame | Container (can contain other small components) |
Label | Displays text or images |
Menu | Menu bar that displays dropdown menus and popup menus |
Menubutton | Menu button of dropdown menu |
Message | Similar to label display text, but can automatically place text within the given width and height |
Radiobutton | Radio button |
Text | Formatted text display, supports embedded images and text, and allows displaying and editing text with different styles and properties |
Start a window
When making a visual thing, the first thing that comes to mind is definitely a window
A window has many components, such as title, ico, size, bd, and menus.
import tkinter import os from tkinter import * class Calculator(object): """Calculator""" def __init__(self): self.tk=tkinter.Tk() #Instance self.tk.title('Calculator') self.tk.minsize(370,460) self.tk.maxsize(400,400) #You can also use self.tk.resizable(0, 0) to disable resizing self.tk.iconbitmap(os.getcwd())+'/favicon.ico') def start(self): self.tk.mainloop() if __name__ == '__main__': NewCalculator=Calculator() NewCalculator.start()
Here, a basic window is generated, and the role of mainloop() within it
If we delete it, the window will flash and disappear, and it is designed to prevent this situation
Panel display
After making a calculator, it is definitely necessary to show the calculation result first, which requires generating a display panel here
Of course, we will also naturally associate with the font settings of displayed content and other specific needs, with examples shown in the following code
.... import tkinter.font as tkfont .... #Font settings self.EntryFont=tkfont.Font(self.tk, size=...13) self.ButtonFont=tkfont.Font(self.tk, size=...12) #Panel display self.count=tkinter.StringVar() self.count.set('0') self.label=tkinter.Label(self.tk,bg='#EEE9E9',bd='3',fg='black',anchor='center',font=self.EntryFont,textvariable=self.count) self.label.place(y=10,width=380,height=40) ....
Among them, there are some parameters in the panel Lable of tkinter, and the ones used here basically meet the common needs
Among them, bg is the background color, fg is the foreground color, changing the color of the content, anchor is the position of the content in the panel, as shown in the figure below
direction | example | table |
---|---|---|
nw | n | ne |
w | center | e |
sw | s | se |
Regarding the positioning of the panel and the Button behind, many methods can be used, place can accurately locate, and also pack(), grid() can be used
It is better for the calculator to use place, which can accurately locate each control
The font can also be directly added as a parameter in Lable(), for example, font=("Arial,6")
textvariable is equivalent to the role of 'listening', binding tkinter's string, you can change the content of the panel conveniently with the set() method
button, input box settings
button, the parameters of the input box and the panel inside are similar
self.NumButton=tkinter.Button(master=self.tk,relief=GROOVE,bg='#EE6A50',text=self.ButtonList[0], font=self.ButtonFont,command=self.clear) self.NumButton.place(x=30,y=80,width=70,height=55) self.shiEntry=Entry(self.baoxianTk,validate='key',validatecommand=(self.checkNum,'%P'),font=self.EntryFont) self.shiEntry.place(x=190,y=80)
The same is through the setting of parameters such as bg to establish the basic style, but here it will bind events through command, similar to the .click in JQ
The place here is also used to be able to accurately locate, and the relief represents the style of the Button
relief=FLAT or GROOVE or RAISED or RIDGE or SOLID or SUNKEN
Among which, delete the input content of the input box
text.delete(10) # Delete index value10the value text.delete(10, 20) # Delete index values from10to2Values before 0 text.insert(0, END) # Delete all values
Input restriction
When designing features, we may need users to input numbers, etc., here we can limit this
The Button parameter specifies when to execute the function bound by validatecommand, using %P can obtain the input content in real time
When the validate option is specified as key, any input operation will be intercepted, at this time returning True will allow the white energy to be input into the Entry
self.checkNum=self.baoxianTk.register(self.validateNum) self.gerenEntry=Entry(self.baoxianTk,validate='key',validatecommand=(self.checkNum,'%P'),font=self.EntryFont) self.gerenEntry.place(x=190,y=190) # Validate if the input is a number def validateNum(self,content): if content.isdigit() and int(content)>=0 or content=="": return True else: return False
The validateNum() function can be changed according to your needs
The values that can be set for the validate option to enable validation are:
Name | event |
---|---|
focus | Validate when the Entry component gains or loses focus |
focusin | Validate when the Entry component gains focus |
focusout | Validate when the Entry component loses focus |
key | Validate when the input box is edited |
all | Validate when any of the following situations occur |
Symbol design expansion
I have added % in this small calculator/, symbols such as sqrt
My approach for their implementation is to check the content of the button passed before adding it to the panel
If it is one of these three symbols, corresponding treatment should be given
Among which, if it is a multi-digit number or a number with a sign
Cannot be transformed directly, you need to judge the number of digits of the number you want to transpose, and my specific method is as follows
def checkList(self): result=0 locate=-1 listSum=0 for length in range(0,len(self.inputlist)): if re.findall(r'[-+*/]',str(self.inputlist[length])): result=1 if length>locate: locate=length else: pass if result==1: for i in range(locate+1,len(self.inputlist)): listSum+=int(self.inputlist[i])*(10**(len(self.inputlist)-i-1)) else: for j in range(0,len(self.inputlist)): listSum+=int(self.inputlist[j])*(10**(len(self.inputlist)-j-1)) return listSum,locate # Add button def addButton(self,button): if button==self.ButtonList[18]: listSum,locate=self.checkList() if locate==-1: self.inputlist=[str(round(eval('1/'+str(listSum)),5))] else: for k in range(locate+1,len(self.inputlist)): del self.inputlist[k] self.inputlist.append(str(round(eval('1/'+str(listSum)),5)) elif button==self.ButtonList[19]: pass elif button==self.ButtonList[20]: pass else: self.inputlist.append(button) self.count.set(self.inputlist)
About lambda
Baidu Encyclopedia: Lambda expression is a special form of function definition in Python, which can be used to define an anonymous function
Unlike other languages, the function body of Python's Lambda expression can only have a single statement, which is the return value expression statement
After searching for more articles, I understand more, Lambda function can be said to play a 'callback' role for the button
If we do not use Lambda for intermediate function delay callback, the function bound to command will be called at the same time as creating the button
The difference between the following two lines of code is that the second line directly executes the knobDown function when creating
self.NumButton=tkinter.Button(master=self.tk, relief=GROOVE, bg='#BFEFFF', text=self.ButtonList[20], font=self.ButtonFont, command=lambda:self.knobDown(self.ButtonList[20)) self.NumButton=tkinter.Button(master=self.tk, relief=GROOVE, bg='#BFEFFF', text=self.ButtonList[20], font=self.ButtonFont, command=self.knobDown(self.ButtonList[20))
For a more detailed explanation, you can refer to the last two articles at the end, the predecessors write well
About the radio button
I wanted to implement the example given in the PPT-The extension of mortgage calculation, but I gave up because of the BUG in this radio button
The following example is copied from the internet, but I forgot the specific URL
It is through the variable binding an IntVar() that the value of the Radiobutton can be obtained through the .get() method
#!/usr/bin/env python import tkinter from tkinter import * import tkinter.font as tkfont root=tkinter.Tk() val=tkinter.IntVar() val.set(0) def func1 if val.get() == 0: label.configure(text='radio 0') else: label.configure(text='radio 1 label = tkinter.Label(root, text='radio 0') label.pack() r0 = tkinter.Radiobutton(text = 'radio0', variable = val, value = 0) r0.pack() r1 = tkinter.Radiobutton(text = 'radio1variable = val, value = 1) r1.pack() b = tkinter.Button(root, text='button', command=func1) b.pack() root.mainloop()
Packaging
C:\Users\bayi\Desktop\shiyan\progrem (venv) λ pip install pyinstaller C:\Users\bayi\Desktop\shiyan\progrem (venv) λ pyinstaller -F -w -i favicon.ico run.py
At first, because the code set the ico icon to the following code in the first line
There is a problem with the path recognition of the packaging path under Windows, so move the icon to a place with a short path
Modify it to an absolute path and it's OK (the second line of the code below, exe and ico should be placed in the same directory)
self.baoxianTk.icobitmap('favicon.ico') self.baoxianTk.iconbitmap(os.getcwd())+'/favicon.ico')
Preview of the effect
Although it is learned on the spot and based on others' old knowledge, it is still very rewarding after success (and I seem to be very picky about graphic design...)
It takes a long time to adjust colors and styles, including the front-end of the previous crawler
Summary
That's all for this article. I hope the content of this article has certain reference value for everyone's learning or work. If you have any questions, you can leave a message for communication. Thank you for your support of the Yell Tutorial.
Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email for reporting, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)