PCPP 32 10x PCPP Certified Professional Python Programmer 1 · Free Practice Question Easy
Question 8
Consider the following code snippet using Tkinter:
- from tkinter import Tk, Button, StringVar
- root = Tk()
- root.geometry('200x200')
- str_var = StringVar()
- str_var.set("Hello, Tkinter!")
- def update_text():
- str_var.set("Button clicked!")
- button = Button(root, textvariable=str_var, command=update_text)
- button.pack()
- root.mainloop()
What happens when the button in the running application is clicked?
-
A
The text "Button clicked!" is printed to the console.
-
B
The text on the button changes to "Button clicked!".
-
C
An error occurs because
textvariableis not a valid option for aButtonwidget. -
D
The text on the button changes to "Hello, Tkinter!".
Reveal correct answer
Correct answer: B
A.
While the update_text function is indeed invoked when the button is clicked, it doesn't print anything to the console. Instead, it changes the value of str_var.
B.
The Button widget is configured with textvariable=str_var, which means the text on the button reflects the current value of str_var. When the button is clicked, the update_text function changes str_var to "Button clicked!", so the text on the button changes to reflect this.
C.
textvariable is indeed a valid option for a Button widget. It allows the text on the button to be dynamically updated based on a Tkinter variable.
D.
The initial text on the button is "Hello, Tkinter!", but when the button is clicked, the update_text function changes str_var to "Button clicked!", causing the text on the button to change to "Button clicked!".
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
