Use the pack bureau manager: the manager layout widget

1. Description

        In this tutorial, we will see how to make a login UI. Today's tutorial will focus on using Tkinter's packlayout managers.

2. Design the user interface

        What are layout managers ? When creating a graphical interface, the widgets in the window must have a way of being arranged relative to each other. For example, placing a widget can be done using its relative position to other widgets or by specifying a pixel location to define its position. In Tkinter, there are three types of layout managers -- pack,place,grid . Each manager uses a different method to help us arrange widgets. To learn more about the differences between these three methods, check out this tutorial .

        Login UI is everywhere, on your phone, computer, bank and more. The user's information must be collected and checked to see if the input matches data already in the system.

        Take a look at the above image of the login UI. We need to create a label to display the text "Login". Then, add the user's personal image. Next are fields where they can enter their username, password, and check a box if they want the computer to remember their information next time. Since it is beyond the scope of this tutorial, the "forgot password" link is just a placeholder.

3. Package Layout Manager

        So what is a bag? The easiest way to think about it is that the pack() method turns each individual widget into a block. Each widget has its own size, and the package manager combines them as if using real blocks.

        Each widget has its own size and parameters. Of course, you can change these to better suit your needs. Once the size of each widget is determined, the manager does the work of arranging them in the window.

        Let's take a moment to understand some basics of package layout managers. With pack, the manager can vertically stack widgets on top of each other like blocks. Of course, you can also achieve a horizontal layout by changing the side parameter to "left" or "right". You can also change the widget's height, width and position. Some of the more useful parameters of the package manager are listed below:

  • side -- specifies the general position of the widget in the window, the parameters are 'top', 'bottom', 'left', 'right' (default 'top').
  • fill – Which direction you want the widget to fill the parent window, you can choose "x", "y" direction or "both".
  • padx, pady - Number of pixels around the widget to create padding between other widgets, for horizontal or vertical padding.
  • ipadx, ipady -- How many pixels to use for internal padding of the widget, also for horizontal or vertical padding
  • Expand - Set to True if you want the widget to stretch when the parent window is expanded. The default value is False.
  • achor anchor - The position at which the widget is placed within the parent widget, specified by 'n', 's', 'e', ​​'w' or some combination thereof. Defaults to "center".

    

4. Use packages to create a simple UI

         The geometry manager package is useful for GUIs in general. Below is a simple example of how to use pack() to create a UI and arrange widgets in a window.

python
from tkinter import *

root = Tk()
root.title("Using Pack")
root.geometry("300x100")  # set starting size of window
root.config(bg="skyblue")

# Example of how to arrange Button widget using pack
button1 = Button(root, text="Click me")
button1.pack(side="left")

# Example of how to arrange Label widgets using pack
label1 = Label(root, text="Read me", bg="skyblue")
label1.pack(side="right")
label2 = Label(root, text="Hello", bg="purple")
label2.pack(side="right")

def toggled():
    '''display a message to the terminal every time the check button
    is clicked'''
    print("The check button works.")

# Example of how to arrange Checkbutton widget using pack
var = IntVar()  # Variable to check if checkbox is clicked, or not
check = Checkbutton(root, text="Click me", bg="skyblue", command=toggled, variable=var)
check.pack(side="bottom")
root.mainloop()

        First, we import the Tkinter module and create the main window on lines 1-6. root

Example of how pack can arrange widgets

        An example of how pack arranges widgets.

        In lines 9-10 we create our first widget. Notice how the argument on line 10 is used to arrange the widgets on the left side of the window. Next, let's see what happens if we want to place the widget on the right side (Lines 14-17). Here we arrange two tabs in the window using the following. Note how it is placed on the right. In order to be placed below, you need to create a widget to contain them. Keep in mind that if you use a complex GUI, your code will also become more complex. Below is an example of Login UI.Buttonside="left"side="right"label2label1label2label1Framepack

        Finally, let's look at the bottom. Pack automatically centers widgets in their respective areas. Changing the value to can help move the checkbox a bit to the left. Checkbutton anchor 'w'

5. Create a login UI

        Now let's get to the login UI! Below is the full code for the GUI.

python
from tkinter import *

root = Tk()
root.title("Login UI using Pack")
root.geometry("400x320")  # set starting size of window
root.maxsize(400, 320)  # width x height
root.config(bg="#6FAFE7")  # set background color of root window

login = Label(root, text="Login", bg="#2176C1", fg='white', relief=RAISED)
login.pack(ipady=5, fill='x')
login.config(font=("Font", 30))  # change font and size of label

# login image
image = PhotoImage(file="redhuli_favicon.gif")
img_resize = image.subsample(5,5)
Label(root, image=img_resize, bg="white", relief=SUNKEN).pack(pady=5)

def checkInput():
    '''check that the username and password match'''
    usernm = "Username301"
    pswrd = "Passw0rd"
    entered_usernm = username_entry.get()  # get username from Entry widget
    entered_pswrd = password_entry.get()  # get password from Entry widget

    if (usernm == entered_usernm) and (pswrd == entered_pswrd):
        print("Hello!")
        root.destroy()  

    else:
        print("Login failed: Invalid username or password.")

def toggled():
    '''display a message to the terminal every time the check button
    is clicked'''
    print("The check button works.")

# Username Entry
username_frame = Frame(root, bg="#6FAFE7")
username_frame.pack()

Label(username_frame, text="Username", bg="#6FAFE7").pack(side='left', padx=5)

username_entry = Entry(username_frame, bd=3)
username_entry.pack(side='right')

# Password entry
password_frame = Frame(root, bg="#6FAFE7")
password_frame.pack()

Label(password_frame, text="Password", bg="#6FAFE7").pack(side='left', padx=7)

password_entry = Entry(password_frame, bd=3)
password_entry.pack(side='right')

# Create Go! Button

go_button = Button(root, text="GO!", command=checkInput, bg="#6FAFE7", width=15)

go_button.pack(pady=5)

# Remember me and forgot password
bottom_frame = Frame(root, bg="#6FAFE7")
bottom_frame.pack()

var = IntVar()

remember_me = Checkbutton(bottom_frame, text="Remember me", bg="#6FAFE7", command=toggled, variable=var)
remember_me.pack(side='left', padx=19)

# The forgot password Label is just a placeholder, has no function currently
forgot_pswrd = Label(bottom_frame, text="Forgot password?", bg="#6FAFE7")
forgot_pswrd.pack(side="right", padx=19)

root.mainloop()

        Package layout managers are best suited for simple layouts. The login UI is mainly composed of some vertical widgets stacked on top of each other. So this is a perfect opportunity to try pack().

        First set the root window, its size and background color. Then, create the first two widgets (login label and user image) and place them in the root window. These two are the easiest as they are just two widgets arranged vertically.

        For the username, password, and "remember me" areas, these areas are a little more complicated. Because they are two different widgets per set, each arranged horizontally, and because we already have the login and image widgets arranged vertically, we need to create a frame widget for each. These frames will also be stacked under the widgets we've already created. Each frame will hold two widgets.

        Let's look at the first one. On line 38, we create the username_frame object which will contain the "username" text and the Entry widget for username input name. You'll create them on lines 43-44. Note how the side parameters are "left" and "right" to arrange them horizontally in the username_frame. We create the other two regions in a similar manner. I won't include their descriptions here because they are similar.

        After the user enters information and clicks the "GO!" button, we call checkInput() (lines 18 - 30) to check that the information entered by the user matches the information already stored in the program on lines 20 and 21. If it matches, the window is closed by calling root.destroy().

6. Summary

        In this tutorial, we saw how to use the pack method by creating two separate UIs. We also looked at how to arrange widgets in simple and slightly more complex layouts.

        Of course, there are many ways to improve the appearance and functionality of this GUI. On the one hand, you can actually allow users to create their own usernames and passwords, and write that information to the output file. Another thing you can do is allow the UI to store user information with a "remember me" check button. Also, you can change the "forgot password" label to a link that redirects the user to a new window. Additionally, you can let users choose their own images for their profiles by searching local files on their computers.

Guess you like

Origin blog.csdn.net/gongdiwudu/article/details/132656821