Basic application of tkinter container control in Python

Article directory

Frame Frame

                         . The syntax of the construction method is as follows:

#Parent can be omitted
 Frame (parent, options,...)

Parameters:

  • First parameter: parent object, which window this framework will be built in
  • The second parameter: options. The parameters are as follows
parameter Meaning
borderwidth Boundary width
Two pixels by default
bd Boundary width
Two pixels by default
bg background color
background background color
cursor Shape when mouse cursor moves over frame
height High, unit is character high
highlightbackground Color when frame does not get focus
highlightcolor Color when frame gets focus
highlighthickness Thickness when frame gets focus
relief The frame frame can be controlled from this
The default is relief=FLAT
width The width of the frame, in pixels
It will automatically adjust to the actual width when omitted

Preliminary application of Frame

Example: set up three frames with different background colors

import tkinter

# Create main window
root = tkinter.Tk()
for i in ["red", "orange", "lightgreen"]:
	# root is omitted here
    tkinter.Frame(bg=i, height=50, width=150).pack()

root.mainloop()

Operation result:

The framework is also a Widget control, so finally, you need to use the control configuration manager to package and locate, that is, pack, grid, etc

Example: let the mouse cursor have different shapes on different frames at the same time

import tkinter

# Create main window
root = tkinter.Tk()
# Using dictionary to store frame color and cursor shape
x = {"red": "cross", "orange": "boat", "lightgreen": "clock", "lightblue": "star"}

for i in x:
    # Establish four different background color frames and cursor shapes
    tkinter.Frame(bg=i, cursor=x[i], height=50, width=150).pack(side=tkinter.LEFT)

root.mainloop()

Operation result:

Create Widget controls within the framework

                         ,

A = Frame(root, ...)     # Return frame object A
button = Button(A, ...)  # Frame object A is the parent container of button function buttons

Example:

import tkinter

# Create main window
root = tkinter.Tk()
# Establish the upper framework
frameUp = tkinter.Frame(root, bg="lightyellow")
frameUp.pack()
# First button of upper frame
butOne = tkinter.Button(frameUp, text="One", fg="red")
butOne.pack(side=tkinter.LEFT, padx=5, pady=5)
# Upper frame second button
butTwo = tkinter.Button(frameUp, text="Two", fg="orange")
butTwo.pack(side=tkinter.LEFT, padx=5, pady=5)
# Upper frame third button
butThree = tkinter.Button(frameUp, text="Three", fg="lightgreen")
butThree.pack(side=tkinter.LEFT, padx=5, pady=5)
# Establish the lower frame
frameLow = tkinter.Frame(root, bg="lightblue")
frameLow.pack()
# Button to create lower frame
butLast = tkinter.Button(frameLow, text="Last")
butLast.pack(side=tkinter.LEFT, padx=5, pady=5)


root.mainloop()

Operation result:

Flexible use of relief attribute

You can use the relie property to build Widget control in the framework

Example:

import tkinter

# Create main window
root = tkinter.Tk()
frameOne = tkinter.Frame(width=150, height=80, relief=tkinter.GROOVE, borderwidth=5)
frameOne.pack(side=tkinter.LEFT, padx=5, pady=5)

frameTwo = tkinter.Frame(width=150, height=80, relief=tkinter.RAISED, borderwidth=5)
frameTwo.pack(side=tkinter.LEFT, padx=5, pady=5)

frameThree = tkinter.Frame(width=150, height=80, relief=tkinter.RIDGE, borderwidth=5)
frameThree.pack(side=tkinter.LEFT, padx=5, pady=5)

root.mainloop()

Operation result:

Create a check box in a frame with the raised attribute

Example:

import tkinter

# Create main window
root = tkinter.Tk()
frame = tkinter.Frame(width=150, height=80, relief=tkinter.RAISED, borderwidth=5)
frame.pack(padx=10, pady=10)
label = tkinter.Label(frame, text="Choose your favorite food")
label.pack()
foodOne = tkinter.Checkbutton(frame, text="hot dry noodles")
foodOne.pack(anchor=tkinter.W)
foodTwo = tkinter.Checkbutton(frame, text="Deep-Fried Dough Sticks")
foodTwo.pack(anchor=tkinter.W)
foodThree = tkinter.Checkbutton(frame, text="Chinese doughnut")
foodThree.pack(anchor=tkinter.W)

root.mainloop()

Operation result:

Additional support for the relief attribute

In the standard Frame framework, the relief attribute is not fully supported.

For example, the solid and sunken properties, where you can use the Frame and Style modules of tkinter.ttk

Example:

import tkinter
from tkinter.ttk import Frame, Style

# Create main window
root = tkinter.Tk()
# Switch to Style
style = Style()
# Use alt to support Style instead
style.theme_use("alt")

fm1 = Frame(root, width=150, height=80, relief="flat")
fm1.grid(row=0, column=0, padx=5, pady=5)

fm2 = Frame(root, width=150, height=80, relief="groove")
fm2.grid(row=0, column=1, padx=5, pady=5)

fm3 = Frame(root, width=150, height=80, relief="raised")
fm3.grid(row=0, column=2, padx=5, pady=5)

fm4 = Frame(root, width=150, height=80, relief="ridge")
fm4.grid(row=1, column=0, padx=5, pady=5)

fm5 = Frame(root, width=150, height=80, relief="solid")
fm5.grid(row=1, column=1, padx=5, pady=5)

fm6 = Frame(root, width=150, height=80, relief="sunken")
fm6.grid(row=1, column=2, padx=5, pady=5)


root.mainloop()

Operation result:

In the above program, the Frame in tkinter.ttk module should be used as support to display the relief Frame normally.

The alt parameter is mainly the parameter supported for relief in this mechanism

LabelFrame

Basic concept of label framework

                        

Labelframe (parent, options,...)

Parameters:

  • First parameter: parent object, which window this label frame will be built in
  • The second parameter: options. The parameters are as follows
parameter Meaning
borderwidth Boundary width
Two pixels by default
bd Boundary width
Two pixels by default
bg background color
background background color
cursor Shape when mouse cursor moves over button
font Font of text in label frame
height High, unit is character high
highlightbackground Color when frame does not get focus
highlightcolor Color when frame gets focus
highlighthickness Thickness when frame gets focus
labelAnchor Set where to place labels
relief The frame frame can be controlled from this
The default is relief=FLAT
text Label content
width The width of the frame, in pixels
It will automatically adjust to the actual width when omitted

Example:

import tkinter

# Create main window
root = tkinter.Tk()
textFirst = "Welcome to login"
photo = tkinter.PhotoImage(file="1.png")
Logo = tkinter.Label(root, image=photo, text=textFirst, compound=tkinter.BOTTOM)
Logo.pack()

# LabelFrame label frame
labelFrame = tkinter.LabelFrame(root, text="Login box")

accountLabel = tkinter.Label(labelFrame, text="Account number")
accountLabel.grid(row=0, column=0)

accountEntry = tkinter.Entry(labelFrame)
accountEntry.grid(row=0, column=1)

passWd = tkinter.Label(labelFrame, text="Password")
passWd.grid(row=1, column=0)

passWdEntry = tkinter.Entry(labelFrame, show="*")
passWdEntry.grid(row=1, column=1)

labelFrame.pack(padx=10, pady=5, ipadx=5, ipady=5)

root.mainloop()

Operation result:

Use label frame for check boxes

The    tag framework has a wide range of applications and is often used to organize option buttons or check boxes

Example:

import tkinter

def send():
    x = ""
    for j in cheakboxs:
        # This is actually cheakboxs[j].get() == True
        # True if checked
        # If it is not checked, the returned value is False
        if cheakboxs[j].get():
            x = x +foods[j] + "\n"
    print(x)
# Create main window
root = tkinter.Tk()

# LabelFrame label frame
labelFrame = tkinter.LabelFrame(root, text="Choose your favorite food")
foods = {0: "Dumplings", 1: "Spring Rolls", 2: "Tangyuan(glutinous rice ball)", 3: "chaos", 4: "hot dry noodles"}
# It is responsible for giving the dictionary key a value of False or True, which is used to check whether it is checked
cheakboxs = {}
for i in range(len(foods)):
    # This is equivalent to {0: False, 1: False, 2: False, 3: False, 4: False}
    cheakboxs[i] = tkinter.BooleanVar()
    # True only if checked
    tkinter.Checkbutton(labelFrame, text=foods[i], variable=cheakboxs[i]).grid(row=i + 1, sticky=tkinter.W)

labelFrame.pack(padx=10, pady=5, ipadx=5, ipady=5)
button = tkinter.Button(root, text="Submission", width=10, command=send)
button.pack()

root.mainloop()

Operation result:

Top level window

The basic concept of Toplevel window

   the function of this control is similar to Frame, but the container generated by this control is a separate window with its own title bar and border. His construction method syntax is as follows:

Toplevel(options, ...)

Parameters:

  • The first parameter: options. The parameters are as follows
parameter Meaning
borderwidth Boundary width
Two pixels by default
bd Boundary width
Two pixels by default
bg background color
background background color
cursor Shape when the mouse cursor is over the Toplevel window
font Glyph
fg Text foreground color
height Window height
width Window width
Basic operation of Toplevel window

Example:

import tkinter

root = tkinter.Tk()

rootTwo = tkinter.Toplevel()
tkinter.Label(rootTwo, text="Python!!!").pack()
root.mainloop()

Operation result:

After the two windows appear and the Toplevel window is closed, the original main window can still be used. But if the main window is closed, the Toplevel window will close automatically

Example: set the title and size of the Toplevel window

import tkinter

root = tkinter.Tk()

rootTwo = tkinter.Toplevel()
rootTwo.title("Toplevel")
rootTwo.geometry("200x150")
tkinter.Label(rootTwo, text="Python!!!").pack()
root.mainloop()

Operation result:

Use the button to pop up the top level window

Example:

import tkinter
import random


def show():
    num = random.randrange(1, 10)
    t1 = tkinter.Toplevel()
    t1.geometry("100x80")
    t1.title("Toplevel")
    # Bottom up left right center
    # expand whether to fill additional parent container space
    tkinter.Label(t1, text=num).pack(fill=tkinter.BOTH, expand=True)


root = tkinter.Tk()
button = tkinter.Button(root, text="Please click", command=show)
button.pack()

root.mainloop()

Operation result:

Thank you for watching. I will keep updating. If there are any mistakes or suggestions, please contact me personally

Published 35 original articles, won praise 37, visited 4263
Private letter follow

Tags: Attribute Python Spring Windows

Posted on Sat, 14 Mar 2020 23:13:03 -0400 by sanstenarios