PCPP 32 10x PCPP Certified Professional Python Programmer 1 · Free Practice Question Medium
Question 34
You are developing a GUI application using Tkinter in Python. The application includes a Label at the top, a Text widget for multiline text input in the middle, and a Button at the bottom. You want the Label to be centered horizontally at the top, the Text widget to expand and fill the entire middle section, and the Button to be centered horizontally at the bottom. You decide to use the pack() geometry manager to achieve this layout. Here's the code snippet:
- import tkinter as tk
- root = tk.Tk()
- label = tk.Label(root, text="Enter your text below:")
- label.pack(side=tk.TOP, pady=10)
- text = tk.Text(root)
- text.pack(expand=True, fill=tk.BOTH, padx=10, pady=10)
- button = tk.Button(root, text="Submit")
- button.pack(side=tk.BOTTOM, pady=10)
- root.mainloop()
Which of the following statements about this code is correct?
-
A
The
Labelwill be centered horizontally at the top because theside=tk.TOPoption places it at the top and thepady=10option adds vertical padding. -
B
The
Textwidget will not fill the entire middle section of the window becauseexpand=Trueshould be set toFalsewhen usingfill=tk.BOTH. -
C
The
Buttonwill be centered horizontally at the bottom, but it might overlap with theTextwidget because thepack()method does not guarantee non-overlapping widgets. -
D
To ensure the
Textwidget expands correctly, theside=tk.LEFToption should be added to thepack()method.
Reveal correct answer
Correct answer: A
A.
The side=tk.TOP option places the Label at the top of the window, and since no other options affect the horizontal alignment, the Label will be centered horizontally by default. The pady=10 option adds 10 pixels of vertical padding on both the top and bottom of the Label, which helps to create space around it.
B.
The Text widget will fill the entire middle section of the window because the combination of expand=True and fill=tk.BOTH ensures that the Text widget expands both horizontally and vertically to fill the available space.
C.
The Button will be centered horizontally at the bottom without overlapping the Text widget. The pack() method stacks widgets in the order they are packed, and since each widget has its own allocated space, they will not overlap.
D.
The side=tk.LEFT option is not necessary and would misalign the Text widget. The current configuration with expand=True and fill=tk.BOTH correctly allows the Text widget to expand and fill the available space in the middle of the window.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
