Life is short, learn Python!

Graphical user interfaces (GUIs) are interfaces that provide flexibility for user interaction, and many people want to add a visual interface to their Python applets. It is beautiful and interactive. Common Python GUI libraries are: Tkinter, PyQt5, Kivy, wxPython, PySimpleGUI, and so on. These useful and interesting modules will continue to be introduced in Python.

This article will first introduce the main functions of Tkinter based on practical cases.

Before we start, we need to get to know Tkinter.

First acquaintance with Tkinter

Tkinter, a third party library for GUI programming. Is one of the most popular packages that allows you to build guIs in Python!

GUI stands for GraphicalUser Interface, a programming mode distinguished from the black command line of the “console” that most programming languages touch. Tkinter is the Python interface to Tk.

Advantages and disadvantages of Tkinter

  1. Easy to learn, compared to PyGtk, PyQt, etc.

  2. Most scripting languages pride themselves on the fact that they can produce powerful GUI interfaces with very little code, as opposed to languages like C++;

  3. Cross-platform;

  4. Built into Python, we do not need to separate to install, is a lot of convenience, is also a Python standard;

  5. The disadvantage is that the function is too simple, the tkinter framework provides too few functions, many functions still need to be manually implemented;

  6. Another disadvantage is that compared with C++, its efficiency is not too high, for some of the screen requirements are very high.

The first Tkinter program

start

import tkinter Import the tkinter module
tkinter._test() Test whether the tkinter package works
Copy the code

The running results are as follows:

Clicking the Quit button here won’t quit, only clicking the X sign will quit the program.

The first program

import tkinter
base = tkinter.Tk()  The class Tk is instantiated, that is, base is an instance of it
base.wm_title('Tk Test') # set the title
base.mainloop() Run the event loop
Copy the code

Running results:

3. Know the components

If you are used to Windows programming, then the “control” a must not be unfamiliar, in fact, components and controls are the same thing, in this book we do not distinguish.

Components – the Label

The English word for a component is “widget.” Buttons, text boxes, and so on can be used as components. We can add several components to a window to enrich its functionality. We often need to specify the size and location of the component. We also need to programmatically specify what the component can do.

The Label tag

Here is an example of code:

import tkinter

base = tkinter.Tk()  # instantiation

base.wm_title('Tk Test')

w1 = tkinter.Label(base,text='Python Label') Create a label and place it on base

w1.pack()

base.mainloop()
Copy the code

Running results:

Code explanation:

1. Label is a class. You can view the corresponding source code in __init__.py.

2. W1 is an instance of Label that has a text attribute that specifies its text content.

3. W1.pack () represents the layout, specifying where to put it (more on that later)

  1. Multi-label applications

For instances of multiple tabs, declare them first and then pack them into Windows separately.

Here is an example of code:

from tkinter import *

root = Tk()

root.wm_title('components')

w1 = Label(root,text='Lightning of Aleski',background='green')
w2 = Label(root,text='Lightning of Aleski',background='blue')
w3 = Label(root,text='Lightning of Aleski',background='yellow')

w1.pack()
w2.pack()
w3.pack()

root.mainloop()
Copy the code

Running results:

Components – the Button

Binding of buttons to functions

The button component is declared with the command attribute, which accepts a function name. Note that the function name is not quoted.

What we’re going to do is when we press this button, it’s going to add a background color random Label to the window that says “I love Python.”

from tkinter import *
import random

color = ['red'.'orange'.'yellow'.'green'.'blue'.'purple'.'black']
def xinLovePython() :
    global root
    b1 = Label(root,text='I like Python',background=random.choice(color))
    b1.pack()

root = Tk()
btn = Button(root,tetx = 'jiuli',command = xinLovePython)
btn.pack()

root.mainloop()
Copy the code

Running results:

Input box

In order to retrieve user information, it became clear that it was not appropriate to keep clicking on the button, so the input box appeared.

Entry field

  1. Partial source code screenshot:
class Entry(Widget, XView) :
    def __init__(self, master=None, cnf={}, **kw) :
        Widget.__init__(self, master, 'entry', cnf, kw)

    def get(self) :
        """Return the text."""
        return self.tk.call(self._w, 'get')
Copy the code
  1. The more important function in the source code is the get function. The get function does not need any parameters when used, and its return value is the content of the input box.

The password

  1. In fact, the password box and the input box is basically the same, are used to input information inside;

  2. If anything, there is only one difference: the password field requires a single character to display the information;

  3. For example, if e is an input field, we can set its show property to make it a password field, i.e. **e[‘ show ‘] = ‘*’ **.

Code examples:

from tkinter import *

def login() :
    s1 = e1.get()
    s2 = e2.get()
    t1= len(s1)
    t2 = len(s2)
    if s1 == 'yyds' and s2 == 'jiuli':
        c['text'] = 'Login successful'

root = Tk() # main interface
l = Label(root,text='Username :') # Label for user name
l.grid(row=0,column=0,sticky=W)

e1 = Entry(root)
e1.grid(row=0,column=1,sticky=E)

l2 = Label(root,text='password:) # Label for password
l2.grid(row=1,column=0,sticky=W)

e2 = Entry(root)
e2['show'] = The '*'
e2.grid(row=1,column=1,sticky=E)

b = Button(root,text='login',command=login)
b.grid(row=2,column=1,sticky=E)

c = Label(root,text=' ')
c.grid(row=3)
root.mainloop()
Copy the code

The results are as follows:

Iv. Layout of Tkinter

There are three common layout methods:

Pack layout

The Pack () layout is so simple that we don’t have to do much setup, just use a pack function.

The following is an example:

from tkinter import *

baseFrame = Tk()

btn1 = Button(baseFrame,text='A',background='red').pack(side=LEFT,expand=YES,fill=Y)
btn2 = Button(baseFrame,text='B',background='blue').pack(side=TOP,expand=YES,fill=BOTH)
btn3 = Button(baseFrame,text='C',background='orange').pack(side=RIGHT,expand=YES,fill=None,anchor=NE)
btn4 = Button(baseFrame,text='D',background='yellow').pack(side=LEFT,expand=NO,fill=Y)
btn5 = Button(baseFrame,text='E',background='green').pack(side=TOP,expand=NO,fill=BOTH)
btn6 = Button(baseFrame,text='F',background='purple').pack(side=BOTTOM,expand=YES)
btn7 = Button(baseFrame,text='G',background='red').pack(anchor=SE)

baseFrame.mainloop()
Copy the code

Running results:

Explanation:

When we use the pack function, the default is to put the pack function on top and then down, and it gives our components a position and size that they think is appropriate. This is the default, and it’s the way we’ve always done it.

The pack function can also take several arguments:

  • The side parameter specifies which direction it is parked in. It can be LEFT, TOP, RIGHT, or BOTTOM, representing LEFT, up, RIGHT, or down.

  • Its fill parameters can be X, Y, BOTH, and NONE, i.e., fill in horizontal, fill in vertical, fill in horizontal, fill in vertical, and fill in NONE;

  • Its expand parameters can be YES and NO, its anchor parameters can be N, E, S, W (NESW represents north, southeast, west, and upper, right, lower, and left respectively) and their combination or CENTER (represents the middle).

  • Its ipadx represents the x direction of the inner margin, and its ipady represents the y direction of the inner margin;

  • Padx is the x direction of the margin, pady is the y direction of the margin;

The grid layout

Grid can be understood as a grid, or a table, and it sets up the interface as a grid of rows and columns into which we insert the elements we want.

The advantage of this layout is that no matter how we drag the window, the relative position does not change, and this layout is super simple.

The following is an example:

from tkinter import *

xin = Tk()

# Entry stands for "Entry box".
Label(xin,text='account:).grid(row=0,sticky= W)
Entry(xin).grid(row=0,column=1,sticky=E)

Label(xin,text='password:).grid(row=1,sticky=W)
Entry(xin).grid(row=1,column=1,sticky=E)

Button(xin,text='login:).grid(row=2,column=1,sticky=W)
xin.mainloop()
Copy the code

Running results:

Place the layout

For the Place layout, there are fewer scenarios;

It uses the place function, which is divided into absolute layout and relative layout. Absolute layout uses x and y parameters, and relative layout uses relx, RELY, relheight, and relwidth parameters.

Five, events,

First of all, what is an event?

What is an event?

  1. The English expression of event is “event”, and most interface programming also involves “event”.

  2. A lot of user operations, such as when we click the mouse, this is an event, and the operating system will generate the corresponding message according to our corresponding event, the operating system passes the message to our application, and then our application executes the corresponding command according to the data incoming from the operating system;

  3. Events are triggered by the user, and messages are generated by the operating system based on events.

Events and their bindings

  1. In fact, we touched on event binding in the button section, using the function bind;

  2. Bind (event type, callback function);

  3. The so-called “callback function” is the function we do not have to call, when the corresponding event occurs, it will automatically call. For example, when our button is pressed, it will be called automatically.

Common Events

  1. < button-1 > indicates that the left mouse Button is clicked, where 1 is changed to 3 means that the right mouse Button is clicked, and 2 means that the middle mouse Button is clicked, which is not commonly used.


  2. indicates that the A key is pressed and can be replaced with another key.

  3. < control-v > indicates that Ctrl and V keys are pressed, and V can be replaced with another key;


  4. means that the key is F1. For Fn series, you can change it at will.

The binding

  1. Not only can an event be bound to a Button, but we saw in the source code that bind is defined in the Misc class, which means that bind can be used by most component classes.

  2. We can make the “label” to simulate the “button”;

  3. Because the Label is the Label class, which inherits from Widget, which inherits from BaseWidget, which inherits from Misc;

  4. It’s not just a label that can emulate a Button. Any component can emulate a Button, just that useful.

Label simulation button

from tkinter import *

root = Tk()

def Monibtn(event) :
    global root
    mbtn = Label(root,text='test')
    mbtn.pack()

l = Label(root,text='Simulate button')
l.bind('<Button-1>',Monibtn)
l.pack()

root.mainloop()
Copy the code

As shown in the figure:

The bind function

There are two other ways to use bind:

Bind_all: a full-program binding that takes the same type of argument as bind and is used for global shortcuts, such as F1, which is used to open help documents.

Bind_class: Binds some classes and takes three parameters, the first is the class name, the second is the event type, and the third is the corresponding operation.

For example, w.bin_class (” Entry, “” < Control-v >”,my_paste) is a Ctrl+V paste that binds all input boxes.

Remove the binding

To approach bindings, we use the unbind method, which is similar to the use of bind;

The unbind method, however, needs only one parameter. It only needs the unbound event type, because it unbinds all callbacks for that bound event type.

Online simple translation program

Finally, we use a case (online simple translation program), to practice Tkinter to create a graphical user interface!

The specific expected results are as follows:

We hope that users can input the query words, obtain the results and then make a request to Baidu Translation to get the results and fill them into the result box.

The core code

Data request

def translate_word(string) :
    url = "https://fanyi.baidu.com/sug"  Request data url link
    data = {
     'kw':string,
    }
    data_url = urllib.parse.urlencode(data)
    req = urllib.request.Request(url=url,data=data_url.encode('utf-8'))
    response = urllib.request.urlopen(req).read()
    res = json.loads(response)
    return res['data'] [0] ['v'].split('; ') [0]
Copy the code

Use urllib method to make data request, get JSON data, and convert it into dictionary. Since there are key value pairs in the translation result, we can extract the result.

interface

root = Tk()
root.title('Little Translator')
root['width'] = 250; root['height'] = 130
Label(root,text='Please enter what you want to translate :',width=15).place(x=1,y=1)
Entry1 = Entry(root,width=20)
Entry1.place(x=110,y=1)
Label(root,text=' ',width=18).place(x=1,y=20)
s = StringVar()
s.set(' ')
Entry2 = Entry(root,width=20,textvariable=s)
Entry2.place(x=110,y=20)
Button1 = Button(root,text='translation',width=8)
Button1.place(x=40,y=80)
Button2 = Button(root, text='empty', width=8)
Button2.place(x=130, y=80)
Button1.bind("<Button-1>",leftClick) # event binding
Button2.bind("<Button-1>",leftClick2) # event binding
Copy the code

As follows:

The function

Translate button function bindings:

def leftClick(evvnt) :
    enstr = Entry1.get() # Get the content of the translated word
    vText = translate_word(enstr) The translation function gets the translation result
    Entry2.config(Entry2,text=vText) The translation result is filled into the second input box
    s.set(' ')
    Entry2.insert(0,vText)
Copy the code

Empty button function bindings:

def leftClick2() :
     s.set(' ')
     Entry2.insert(0.' ') # Empty your translation
Copy the code

Seven, summary

The Tkinter module (“Tk interface “) is an interface to Python’s standard Tk GUI toolkit.

Tkinter provides a large number of components for graphical interface development to create interface programs with complex functions. The cross-platform feature is one of the advantages of Tkinter, which can be used on most Unix platforms, as well as Windows and Macintosh systems. By combining with crawler, Build simple GUI interface applications.

In future articles, we will continue to cover the use of GUI libraries such as PyQt5, wxPython, PySimpleGUI and so on!