程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python Tkinter Library

編輯:Python

brief introduction

Tkinter The module is Python Standard of the system GUI library , It has a set of commonly used graphic components

Basic components

  • Button Button
  • Canvas canvas , Used to draw lines 、 The ellipse 、 Polygons and other shapes
  • Checkbutton Buttons in the form of checkboxes
  • Entry Single line text box
  • Frame frame , Can be used as a container for other components , It is often used to group components Label mark sign , Used to display single line text
  • Listbox List box
  • Menu menu
  • Message Multi-line text box
  • Radiobutton Radio button , Only one radio button in the same group can be selected at any time
  • Scrollbar Scroll bar
  • Toplevel Often used to create new windows

Basic development process

  1. Write common code , For example, database operation
  2. Build the interface , Place components , Set component properties
  3. Write event handling code for components
  4. Start the application , Start message main loop

Usage flow

The import module

import tkinter
from tkinter import *
import tkinter as tk

Create a form object

The form has a title 、 A top-level container of the border , Other components can be added inside , The module objects used are all placed in the form object .
call pack() Method to layout the area of the container .

win = tkinter.Tk()
win.title("2333") # title 
win.geometry("720x480+40+40") # size (720x480), The starting position (40+40)
win.mainloop() # Enter the main event cycle , That is, display the form object .

label

label = tkinter.Label( Container name , Display text or image content , Display position , Text font , Color, etc. )

Button and event handling

When you press a button in the application , An application can trigger an event to perform the corresponding action . stay Python in tkinter Module Button Used to build button objects .

Btn = tkinter.Button( Containers ,text=‘ The text on the button ’)

Use case

import tkinter
win = tkinter.Tk()
win.title("2333")
win.geometry("720x480+40+40")
label = tkinter.Label(win, text = " You are one by one ",font = " Song style ", fg = "#0000ff")
label.pack()
def myClick():
t1 = " Hum, hum, ah, ah, ah "
labelClick = tkinter.Label(win, text = t1)
labelClick.pack()
btn = tkinter.Button(win, text = " Click on the I ", command = myClick)
btn.pack()
win.mainloop()

Interface layout management

Python Defined 3 Two interface layout management methods

Pack Layout

Pack The layout management mode is arranged in the container area according to the creation order of components

  • Pack The common properties of are side and fill
  • Side attribute : Its value is top、bottom、left and right, Respectively indicate that the components are arranged on 、 Next 、 Left 、 Right position . The default is top.
  • Fill attribute : Its value is x、y、both, Respectively means filling x( level ) or y( vertical ) Directional space .
import tkinter
win = tkinter.Tk()
win.title(" Layout ")
win.geometry("720x480")
L1 = tkinter.Label(win, text = "L1", bg = "red")
L1.pack(fill = 'y', side = "left")
L2 = tkinter.Label(win, text = "L2", bg = "green")
L2.pack(fill = 'both', side = "right")
L3 = tkinter.Label(win, text = "L3", bg = "blue")
L3.pack(fill = 'x', side = "left")
win.mainloop()

Place Layout

Place The layout management mode specifies the coordinate position arrangement of components , Also called absolute permutation

lb = Label(root, text='hello Place')
lb.place(relx = 1,rely = 0.5,anchor = CENTER)
lb.place(x=0, y=0, anchor = NW)

grid Layout

Grid layout , Components are placed in cells of a two-dimensional table

Grid Common properties of layouts are row( That's ok )、column( Column )、rowspan( Number of lines occupied by the component )、columnspan( Number of columns occupied by components )

from tkinter import *
win = tkinter.Tk()
win.title(" Student information collection ")
win.geometry("720x480+10+10")
L1 = Label(win, text = " Student information ", font = "song -20")
L2 = Label(win, text = " Student number ", font = "song -20")
L3 = Label(win, text = " full name ", font = "song -20")
L4 = Label(win, text = " major ", font = "song -20")
L1.grid(row = 0, column = 1)
L2.grid(row = 1)
L3.grid(row = 2)
L4.grid(row = 3)

Text box components

stay python in , The text box Entry Used to receive input data . The text box Entry The basic format of is :
txt = tkinter.Entry( Container name ,width= Width , Text font 、 Color, etc. )

Make a collection of student information

from tkinter import *
win = tkinter.Tk()
win.title(" Student information collection ")
win.geometry("720x480+10+10")
L1 = Label(win, text = " Student information ", font = "song -20")
L2 = Label(win, text = " Student number ", font = "song -20")
L3 = Label(win, text = " full name ", font = "song -20")
L4 = Label(win, text = " major ", font = "song -20")
L1.grid(row = 0, column = 1)
L2.grid(row = 1)
L3.grid(row = 2)
L4.grid(row = 3)
e1 = Entry(win, width = 20, font = "song -20")
e2 = Entry(win, width = 20, font = "song -20")
e3 = Entry(win, width = 20, font = "song -20")
e1.grid(row = 1, column = 2)
e2.grid(row = 2, column = 2)
e3.grid(row = 3, column = 2)
b1 = Button(win, text = " Submit ")
b2 = Button(win, text = " Cancel ")
b1.grid(row = 4, column = 0)
b2.grid(row = 4, column = 1)
win.mainloop()

Content setting and obtaining in text box

To text box Entry The operation of Chinese text content can use StringVar() Object to complete .StringVar() Track the change of variable value , Display the latest value on the interface

step :

  • First turn on the entry Medium textvariable Property is set to StringVal object
  • Re pass StringVar() Object's get() and set() Function to read or output the corresponding character content
  • thus , The latest value is always displayed in the text box

Design a login interface

from tkinter import *
win = tkinter.Tk()
win.title(" Authentication ")
win.geometry("720x480+10+10")
def myClick():
txt = txt2.get()
if(txt == "abc"):
txt3.set("oh*yeah*sir*")
else:
txt3.set(" You are one by one ")
lab1 = Label(win, text = " Please enter a user name ", font = ('song', '16'))
lab2 = Label(win, text = " Please input a password ", font = ('song', '16'))
txt1,txt2, txt3 = StringVar(), StringVar(), StringVar()
txt3.set(" Please enter your user name and password ")
e1 = Entry(win, textvariable = txt1, width = 16, font = "song -16")
e2 = Entry(win, textvariable = txt2, width = 16, show = "*", font = "song -16")
b1 = Button(win, text = " Submit ", command = myClick, font = "song -16")
lab3 = Label(win, textvariable = txt3, relief = "ridge", width = 30, font = ("song", "16"))
lab1.grid(row = 0, column = 0)
lab2.grid(row = 1, column = 0)
e1.grid(row = 0, column = 1)
e2.grid(row = 1, column = 1)
lab3.grid(row = 2, column = 0, columnspan = 2)
b1.grid(row = 2, column = 2)
win.mainloop()

Radio buttons and checkboxes

Radio button Radiobutton And check boxes Checkbutton Is a set of components that represent multiple choices
They have only two states “ Choose / Not selected ”, Its properties and methods are similar

chVarDis = tk.IntVar()

  • This variable records whether the radio box is selected , Can pass chVarDis.get() Get its status , Its status value is int type , Selected as 1; Not selected as 0.
  • in addition , Check box CheckButton Object's select Method means that ,deselect Method means that... Is not selected

Radio buttons

from tkinter import *
win = Tk()
win.title(" Radio buttons ")
win.geometry("720x480+10+10")
txt = StringVar()
txt.set(" Please select ")
lab = Label(win, textvariable = txt, relief = "ridge", width = 30)
chVarDis = IntVar()
check1 = Checkbutton(win, text = "C", variable = chVarDis, state = "disabled")
check1.select()
chVarUn = IntVar()
check2 = Checkbutton(win, text = "Java", variable = chVarUn, state = "disabled")
check2.deselect()
chVarEn = IntVar()
check3 = Checkbutton(win, text = "Python", variable = chVarEn)
check3.select()
lab.grid(row = 0, column = 0, columnspan = 3)
check1.grid(row = 4, column = 0, sticky = W)
check2.grid(row = 4, column = 1, sticky = W)
check3.grid(row = 4, column = 2, sticky = W)
win.mainloop()

Check box

from tkinter import *
win = Tk()
win.title(" A commonplace ")
win.geometry("720x480+10+10")
txt = StringVar()
txt.set(" Please select ")
lab = Label(win, textvariable = txt, relief = "ridge", width = 30) #relief Is to set the border 
chk = [" walnut ", " Carve clear ", " timely rain "]
def radCall():
radSel = radVar.get()
if radSel == 0:
txt.set(chk[0])
elif radSel == 1:
txt.set(chk[1])
elif radSel == 2:
txt.set(chk[2])
print(radSel)
radVar = IntVar()
for i in range(3):
curRad = Radiobutton(win, text = chk[i], variable = radVar, value = i, command = radCall) # Check box value Is the return value of the selected box 
curRad.grid(column = i, row = 5, sticky = W)
lab.grid(row = 0, column = 0, columnspan = 3)
win.mainloop()

Other common components

from tkinter import tkk
  • Label frame LabelFrame
  • Is a container with a border , Other components can be placed in this container ttk.LabelFrame( Upper level vessel ,text=“ The text displayed by the label ”)
  • Drop down list box Combobox
  • A commonly used value selection component , When using the drop-down list box, you must first declare a value variable number=tk.StringVar()
  • This variable records the character value selected in the preset value of the drop-down list box , The default value in the drop-down list box is a tuple .
  • Drop down list box Combobox Construction method of • ttk.Combobox( Containers ,width= Width ,textvariable= Value variable )
  • Scroll text box ScolledText
  • Is a text box with a scroll bar , You can enter multiple lines of text src=scrolledtext.ScrolledText( Containers ,width= Text box width ,height= Text box height )

Create a frame containing labels 、 Drop down list box and scroll text box

from tkinter import ttk, scrolledtext
import tkinter as tk
win = tk.Tk()
win.title("Python Demo components ")
win.geometry("1080x720")
montry = ttk.LabelFrame(win, text = " Label frame ")
montry.grid(row = 0, column = 0, padx = 100, pady = 100)
lable1 = ttk.Label(montry, text = " Select a number ")
lable1.grid(column = 1, row = 0)
def clickMe():
action.configure(text = "Hello" + ' '+ numberChosen.get())
action = ttk.Button(montry, text = " Click me ", command = clickMe)
action.grid(column = 2, row = 1)
num = tk.StringVar()
numberChosen = ttk.Combobox(montry, width = 12, textvariable = num, state = "readonly")
numberChosen['values'] = (1, 2, 4, 42, 100)
numberChosen.grid(column = 1, row = 1)
numberChosen.current(0)
scrolW = 30
scrolH = 3
scr = scrolledtext.ScrolledText(montry, width= scrolW, height = scrolH)
scr.grid(column = 0, columnspan = 3)
win.mainloop()

Dialog box

Tkinter Provides 3 A standard dialog module

  • Message dialog (messagebox)
  • File dialog (filedialog)
  • Color selection dialog (colorchooser)

Message dialog box with no return value

  1. Import module statement of message dialog box import tkinter.messagebox # Message box , The key to the dialog
  2. Message box
    tkinter.messagebox.showinfo(‘ Tips ’,’ Life is too short ’)
  3. Message warning box
    tkinter.messagebox.showwarning(‘ Warning ’,’ There will be heavy rain tomorrow ’)
  4. Error message box
    tkinter.messagebox.showerror(‘ error ’,’ Something went wrong ’)

Message dialog with return value

  1. askokcancel()
    Show... In the dialog box “ determine ” And cancel button , The return values are true or false
  2. askokquestion()
    Show... In the dialog box “ yes ” and “ no ” Button , The return values are yes or no
  3. askretrycancel()
    Show... In the dialog box “ retry ” and “ Cancel ” Button , The return values are true or false
  4. askyesnocancel()
    Show... In the dialog box “ yes ”、“ no ” and “ Cancel ”3 Button , The return values are yes、no or None

File dialog

import tkinter.filedialog

The return values of the file dialog box are file path and file name

Mouse events

stay python in tkinter Module events event Are described by strings : Component object .bind(event,handler)

  • among ,event For events ,handler Functions that handle events
  • The general format of the click event of the mouse button is
    <ButtonPress-n>
    
  • among ,n For mouse buttons ,n by 1 For the left button ,n by 2 Represents the middle key ,n by 3 Right click
    <ButtonPress-1>
    
    It means pressing the left mouse button
  • You can use mouse events event Get mouse position . Coordinates (event.x, event.y) Is the position of the mouse when the event occurs

Example

from tkinter import *
def callback(event):
print("Click at:", event.x, event.y)
s = (event.x, event.y)
txt.set(s)
win = tk.Tk()
win.title(" Mouse events ")
win.geometry("1080x720")
frame = Frame(win, width = 1080, height = 720, bg = "cyan")
frame.bind("<Button-1>", callback)
frame.pack()
txt = StringVar()
L = Label(win, width = 20, textvariable = txt)
L.pack()
win.mainloop()

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved