• Original blog link address
  • PythonProvides a number of graphical development interface library, several commonly usedPython GUIThe library is as follows:
  • Tkinter:TkinterThe module (Tk interface) isPythonThe standard Tk GUI toolkit interface.TkandTkinterCan be in mostUnixPlatform use, can also be applied inWindowsandMacintoshIn the system.Tk8.0Later versions of Windows will implement a native windowing style and work well on most platforms.
  • wxPython:wxPythonIt’s open source software, yesPythonA set of language excellentGUIGraphics library, allowedPythonIt is very easy for programmers to create complete, functionalGUIUser interface.
  • Jython:JythonThe program can work withJavaSeamless integration. In addition to some standard modules,JythonuseJavaThe module.JythonAlmost standardPythonDoes not depend onCAll modules of the language. For instance,JythonThe user interface will be usedSwing.AWTorSWT.JythonCan be compiled dynamically or staticallyJavaThe bytecode

oneTkinterintroduce

  • TkinterisPythonThe standard ofGUILibrary.PythonuseTkinterIt can be created quicklyGUIApplications.
  • Due to theTkinterIs built into thepythonThe installation package, as long as the installation is goodPythonThen I canimport TkinterLibraries, andIDLEAlso useTkinterWritten for a simple graphical interfaceTkinterStill able to cope

Note: The python3. x version uses the library name tkinter, which starts with a lowercase T

import tkinter
Copy the code
  • Create a GUI program
    • 1, import,tkinterThe module
    • 2. Create controls
    • 3, specify the controlmaster, which control belongs to
    • 4, tellGM(geometry manager)A control has been generated

1. The main window

  • iniOSIn each oneAPPEach has a main windowwindowthewindowIt’s the most basic view of the cityView
  • inPythonChinese nursery rhymes will also have a main window, take a look belowtkinterMethod to generate the main window
# main window
import tkinter

Create the main window
window = tkinter.Tk()

# set the title
window.title('Titanjun')

# set window size
window.geometry('400x400')

Enter the message loop
window.mainloop()
Copy the code

Results the following

The main window has the following methods in addition to the above methods

The tunability of the box size represents the variability in the X and y directions respectively
window.resizable(0.0)

# exit
window.quit()

# Refresh page
window.update()
Copy the code

twoTkintercomponent

  • TkinterProvides a variety of controls, such as buttons, labels and text boxes, oneGUIUsed in applications, these controls are often referred to as controls or widgets
  • There are currently 15 kinds of Tkinter components. Here is a brief introduction of these components
controls describe
Label Label control that can display text and bitmaps
Button Button control to display the button in the program
Entry Input control; Used to display simple text content
Checkbutton Multi-check box control; Used to provide multiple choice boxes in a program
Frame Frame control; Displays a rectangular area on the screen, often used as a container
Canvas Canvas control; Displays graphic elements such as lines or text
Listbox Listbox control; inListboxThe widget is used to display a list of strings to the user
Menubutton Menu button control for displaying menu items.
Menu Menu control; Display menu bar, drop-down menu and pop-up menu
Message Message control; Used to display multiple lines of text, andlabelsimilar
Radiobutton Radio button control; Displays the status of a radio button
Scale Range control; Displays a numeric scale for the numeric range of the output
Scrollbar Scroll bar control that is used when content exceeds visual areas, such as list boxes
Text Text control; Used to display multiple lines of text
Spinbox Input control; withEntrySimilar, but you can specify input range values
PanedWindow A plug-in for window layout management that can contain one or more child controls
LabelFrame A simple container control, often used with complex window layouts
tkMessageBox A message box used to display your application

If the previous H5 front-end development or iOS page related development work, should be able to, in fact, these components and other development languages provided by the component function is similar, attributes are similar, let’s first take a look at some common attributes

Attribute values Property description
bg Control’s background color
fg Font color in component
font Sets the font style and size of the text
height Setting control height
width Set the control width
bd Sets the size of the control’s border, 2 pixels by default
relief Set border styles with Falt, sunken, raised, Groove, Ridge, and default flat
text Setting text content
anchor Aim point, control text position, default center (optional: N north, E East, S South, W West, center, NE SE, SW, NW)
justify When displaying multiple lines of text, set alignment between different lines (left, right, center)
wraplength Limits the number of characters that a control can display per line based on width
underline Underline, none by default; The value is the underlined string index. If it is 0, the first character is underlined
padx The padding on the X-axis is the distance between the content of the control and the edge of the control
pady Padding in the y direction

1. Labelcontrols

  • LabelControl to display text and images.
  • LabelOften used to present information rather than interact with the user
  • LabelYou can also bind events like clicks, but not usually
label = tkinter.Label(window,
                      text="I am a little duck.",
                      bg='# 999999',
                      fg='white',
                      font=('bold'.13),
                      justify='center',
                      height=5,
                      width=30,
                      anchor='n'.# wraplength=30
                      underline=3,
                      bd=3,
                      relief='flat'
                      )
# display
label.pack()
Copy the code

According to the effect

Some Properties

  • anchor: Text display position in space (according to the rule of top north, bottom south, left west, right east), the optional value is (N north, E east, S South, W West, Center, NE Northwest, SE southeast, SW southwest, NW northeast)
  • image: Displays the picture

2. Buttoncontrols

  • ButtonControl is a standardTkinterA widget for various buttons that, if clicked with the mouse, may initiate some action
  • ButtonText and images can be displayed
  • Buttons can only display text in a single font, and text can span multiple lines
# set the title
window.title('Titanjun')

# set window size
window.geometry('400x400')

# create button
button1 = tkinter.Button(window,
                         text='button 1',
                         bg='orange',
                         height=3,
                         width=20,
                         bd=3,
                         relief='sunken',
                         activebackground='orange',
                         activeforeground='white',
                         command=action1
                         )
button1.pack()


button2 = tkinter.Button(window, text='Titanjun', height=3, command=window.quit())
button2.pack()

Enter the message loop
window.mainloop()
Copy the code

Effect of style

Some Properties

  • activebackground: The background color of the button when the mouse is over it
  • activeforeground: The text color of the button when the mouse is over it
  • highlightcolor: Use a bright color
  • image: The image to display on the button
  • state: Sets the button component status. The options are normal(default), active, or disabled.
  • command: the button’s binding function method, which accepts a function name without quotation marks

3. EntryThe input

The input control is used to display simple text content, like the UITextField in iOS, as shown in the following example

vari = tkinter.Variable()
entry = tkinter.Entry(window, textvariable=vari)
entry.pack()

# set values
vari.set('very good')
# values
print(vari.get())
print(entry.get())

Read only input box
vari2 = tkinter.Variable()
entry2 = tkinter.Entry(window, textvariable=vari2, state='disabled')
entry2.pack()

# set values
vari2.set('very bad')
print(vari2.get())

# Password input box, no matter what input will display ciphertext
vari3 = tkinter.Variable()
entry3 = tkinter.Entry(window, textvariable=vari3, show=The '@', bg='red', fg='white')
entry3.pack()
Copy the code

Effect of style

Listen for text changes in the input box

  • Here we need to set up three options
  • validate: Sets the listening state of the input box
    • focus: whenEntryValidates when a component gains or loses focus
    • focusin: whenEntryValidates when the component gets focus
    • focusout: whenEntryValidates when the component loses focus
    • key: Validates when the input box is edited
    • all: Verify when any of the above conditions occur
  • validatecommand: Accepts a function that determines whether the text in the input box is valid. This function can only return True or False as the result of the validation
  • invalidcommand: Specifies the function only invalidatecommandThe return value ofFalseIs called when
# main window
import tkinter

Verify the input text
def varileText(a):
    text = entry4.get()
    if text == '1':
        print('for all kind')
        return True
    print('mistakes')
    return False

#
def testInvaild(a):
    print('invaildCommanf is called ')
    return True

Create the main window
window = tkinter.Tk()
# set the title
window.title('Titanjun')
# set window size
window.geometry('400x400')


Verify that the input content meets the requirements
vari4 = tkinter.Variable()
entry4 = tkinter.Entry(window, textvariable=vari4, validate='key', validatecommand=varileText, invalidcommand=testInvaild)
entry4.pack()

Enter the message loop
window.mainloop()
Copy the code

4. TextMultiline text

  • TextThe text component is used to display and process multiple lines of text.
  • inTkinterOf all the components of,TextThe component is incredibly powerful and flexible, and it’s good for multitasking
  • When creating aTextComponent has no content in it. To insert content into it, you can useinsert()As well asINSERTorENDReference no.

4-1. Insert text/controls/images

text = Text(window, bg='yellow', width=40, height=10)
#INSERT Index indicates the insertion at the cursor
text.insert(INSERT,'I Love')
The #END index indicates the insertion at the END
text.insert(END,' you')
text.pack()

def show(a):
    print('All right, you win.')

# text can also insert button images, etc
b1 = Button(text, text='Dot me dot me', command=show)
Create component command in text
text.window_create(INSERT, window=b1)
Copy the code

4 – (2) index

  • IndexesIndex is used to point toTextComponent text location, andpythonLike the sequence index of,TextThe component index is also corresponding to the position between the actual characters
  • Note that the row numbers start with 1 and the column numbers start with 0
  • For example, 2.4 represents the character in row 2 and column 4
from tkinter import *
root = Tk()
text1=Text(root,width=30,height=3)
text1.insert(INSERT,'Index practice')
# range of 1.2 to 1.5
print(text1.get(1.2.1.5))
Copy the code

4-3. Tags in Text

Tags are used to change the style and function of content in a Text component. You can change the font, size, and color of the Text. Tags also allow you to associate Text, embedded components, and images with the keyboard.

text.insert(INSERT, 'Custom tag name')

The first parameter is the name of the custom tag
The second parameter is the start position of the setting, and the third parameter is the end position
The fourth argument is another position
text.tag_add('tag1'.'1.7'.'1.12'.'1.14')

# use the tag_config function to set the tag attributes.
text.tag_config('tag1', font=17, background='blue', foreground='red')
# text.tag_config('tag1', bg='yellow', fg='red')
The new tag overwrites the old tag
Copy the code

4-4. Scroll bar

text = Text(window, bg='yellow', width=100, height=10)
Add the right scroll bar
scroll = Scrollbar()
# side on the side of the form to fill
scroll.pack(side=RIGHT, fill=Y)
text.pack(side=RIGHT, fill=Y)
# Correlation between the two
scroll.config(command=text.yview)
text.config(yscrollcommand=scroll.set)

str = "To Oak Tree -- Shu Ting.......... The N words........... are omitted ' ' '

text.insert(INSERT, str)
Copy the code

Effect of style

5. Checkbutton Multiple options button

  • CheckbuttonTwo states can be represented:OnandOff, you can set the callback function to be invoked whenever this button is clicked
  • Here’s an example: Select different check boxes and different text will be displayed
def update(a):
    message = ' '
    if tag1.get() == True:
        message += 'titan \n'
    if tag2.get() == True:
        message += 'jun \n'
    if tag3.get() == True:
        message += 'coder \n'

    Clear everything in the text
    text.delete(0.0, END)
    Insert new text content
    text.insert(INSERT, message)

The variable to bind
tag1 = BooleanVar()
check1 = Checkbutton(window, text = 'Titan', variable = tag1, command = update)
check1.pack()

tag2 = BooleanVar()
check2 = Checkbutton(window, text = 'Juned', variable = tag2, command = update)
check2.pack()

tag3 = BooleanVar()
check3 = Checkbutton(window, text = 'Coder', variable = tag3, command = update)
check3.pack()


text = Text(window, bg = 'orange', width = 50, height = 5)
text.pack()
Copy the code

Effect of style

6. Radiobutton option box

A Radiobutton is a Radiobutton, that is, only one button can be selected in the same group. When a button is selected, the other buttons are automatically unselected. Different from other controls, it has the concept of a group

def selectorAction(a):
    print(tag.get())

A set of checkboxes bound to the same variable
tag = IntVar()
radio1 = Radiobutton(window, text = 'one', value = 23, variable = tag, command = selectorAction)
radio1.pack()
radio2 = Radiobutton(window, text = 'two', value = 32, variable = tag, command = selectorAction)
radio2.pack()
radio3 = Radiobutton(window, text = 'ten', value = 10, variable = tag, command = selectorAction)
radio3.pack()
Copy the code

Effect of style

To be continued, the later will continue to update the related introduction of other controls……….