Courseiva

CCNA Graphical User Interface Programming Questions

58 questions · Graphical User Interface Programming topic · All types, answers revealed

1
MCQhard

You are implementing a custom Tkinter widget that must validate user input in an Entry field and prevent non-numeric characters from being entered. Which mechanism should you use to intercept and optionally reject each keystroke before it modifies the Entry contents?

A.Use entry.config(state='readonly') and toggle it in a '<FocusIn>' handler.
B.Bind '<Key>' to a handler that deletes the last character if it is not a digit.
C.Bind '<KeyRelease>' to a handler that checks the Entry contents and calls entry.delete(0, tk.END) if invalid.
D.Register a validation function with entry.config(validate='key', validatecommand=(vcmd, '%P')) and return True or False from it.
AnswerD

Tkinter's validation mechanism with validate='key' calls the registered command before each insertion or deletion. The %P substitution provides the prospective value of the Entry after the edit. Returning True accepts the change and False rejects it, which is exactly the behaviour needed to block non-numeric input at the source.

Why this answer

Tkinter's built-in validation support is designed for exactly this purpose. Configuring validate='key' with a validatecommand that receives the %P substitution lets the callback inspect the prospective Entry value and return True to accept or False to reject the edit. This intercepts input before it is applied, which is more reliable than post-hoc key bindings that must undo changes.

Exam trap

The trap here is relying on Key or KeyRelease bindings to filter input, when those run after the default insertion and cannot cleanly prevent a character from being entered.

2
MCQhard

A Tkinter application has a modal dialog implemented as a Toplevel that collects a numeric discount. The dialog's OK button command calls a validator that may raise ValueError, and you want the dialog to stay open with an inline error label rather than crashing the mainloop. The dialog is opened from the main window with dialog.grab_set() followed by main_window.wait_window(dialog). Which approach correctly keeps the error visible and prevents the exception from propagating out of the Tkinter callback?

A.Move the validation into a separate thread and call dialog.destroy() from that thread when validation fails.
B.Call dialog.wait_window(dialog) again inside the OK button command so the dialog blocks until validation succeeds.
C.Wrap the validation logic in try/except ValueError inside the OK button's command, update an error Label's text, and return normally so the callback ends without raising.
D.Set dialog.protocol('WM_DELETE_WINDOW', lambda: None) so the dialog cannot be closed while validation is pending.
AnswerC

Tkinter invokes widget callbacks from the Tcl interpreter, and an uncaught Python exception in a callback is reported through Tkinter's report_callback_exception hook rather than terminating mainloop. Catching ValueError inside the command lets you set the error Label and return normally, so the dialog remains open and the user can correct the input. This is the intended pattern for inline validation in modal Toplevel dialogs.

Why this answer

Inline validation in a modal Toplevel requires the callback to handle its own exceptions and update widget state instead of letting the error escape into Tkinter's global handler. Catching ValueError, writing to the error Label, and returning normally keeps the dialog alive and interactive, which is exactly what the scenario demands. Threading, nested wait_window, and protocol overrides all miss that central point.

Exam trap

The trap here is believing that an exception in a Tkinter callback will crash the application, when it is actually routed to report_callback_exception and the dialog simply fails to show the intended error.

3
Multi-Selectmedium

Which TWO of the following events are commonly bound in Tkinter for mouse interaction?

Select 2 answers
A.<Enter>
B.<Button-1>
C.<Quit>
D.<KeyPress>
E.<MouseMove>
AnswersA, B

`<Enter>` fires when the pointer crosses into a widget's boundary, satisfying the mouse-interaction requirement. Tkinter binds it to the widget under the cursor, generating `<Enter>` on entry and `<Leave>` on exit — distinct from `<Return>`, which is a keyboard event for the Enter key.

Why this answer

In Tkinter, <Enter> (option A) is a standard event that fires when the mouse pointer enters a widget, making it a common mouse-interaction binding. <Button-1> (option B) is also standard and fires when the left mouse button is pressed over a widget, so it is directly a mouse interaction event. By contrast, <Quit> (option C) is not a Tkinter event at all; quitting is typically handled via protocols like WM_DELETE_WINDOW or a command callback. <KeyPress> (option D) is a valid Tkinter event but it is a keyboard event, not a mouse event. <MouseMove> (option E) is not a valid Tkinter event name; mouse motion is bound using <Motion> (or <B1-Motion> for motion while the left button is held).

Exam trap

PCPP1 often tests whether candidates recognize Tkinter's exact event pattern names, so plausible-sounding but non-existent events like <MouseMove> or <Quit> tempt candidates who assume naming conventions from other GUI toolkits.

4
MCQhard

When using the place() geometry manager, what is the purpose of 'relx' and 'rely'?

A.Relative position as a float from 0 to 1.
B.Relative font size.
C.Relative pixel coordinates.
D.Relative Z-index for layering.
AnswerA

relx and rely express widget placement as a float between 0.0 and 1.0, representing a fraction of the master's width and height. This satisfies the stem's relative positioning requirement, unlike absolute x and y, which use pixel offsets.

Why this answer

In Tkinter's place() geometry manager, relx and rely specify the widget's position as a fraction of the parent's width and height, expressed as a float between 0.0 and 1.0. For example, relx=0.5 centers the widget horizontally regardless of the window's actual pixel size. This makes layouts resolution-independent, unlike absolute x/y coordinates.

Exam trap

PCPP1 often tests whether candidates confuse relx/rely (fractional, 0.0–1.0) with the absolute x/y pixel options, or mistakenly associate them with font scaling or Z-order.

How to eliminate wrong answers

Option B is wrong because relative font size is controlled through font specifications (e.g., font=('Helvetica', 12)) or widget scaling, not through relx/rely, which are purely positional. Option C is wrong because relative pixel coordinates are not what relx/rely represent — pixel offsets are given by the absolute x and y options, while relx/rely are fractional proportions of the parent. Option D is wrong because Z-order layering in Tkinter is handled by lift()/lower() and stacking order, not by relx/rely, which only affect placement.

5
MCQmedium

You are developing a Tkinter application that includes a Button widget. When the user clicks the button, you need to execute a function named handle_click that accepts no arguments. Which approach correctly associates this function with the button's click event?

A.button = Button(root, text='Click', command='handle_click')
B.button = Button(root, text='Click', command=lambda: handle_click)
C.button = Button(root, text='Click', command=handle_click)
D.button = Button(root, text='Click', command=handle_click())
AnswerC

Passing the function name without parentheses assigns the function object itself as the command callback. Tkinter stores this callable and invokes it each time the button is clicked, which is the correct way to bind a handler. This approach works for any callable that takes no arguments, and it is the standard pattern for Tkinter event handling.

Why this answer

The command option of a Tkinter Button expects a callable object that will be invoked when the button is clicked. Passing the function name without parentheses provides that callable. Using parentheses calls the function immediately, a lambda that returns the function does not call it, and a string is not callable.

Therefore, the only correct approach is to pass the function object itself.

Exam trap

The trap here is confusing function invocation with function reference, leading to immediate execution or no execution at all.

6
Multi-Selecthard

Which TWO of the following are valid ways to add padding to a widget in the grid layout?

Select 2 answers
A.margin=10
B.spacing=10
C.gap=10
D.padx=10
E.pady=10
AnswersD, E

padx=10 is a valid grid() keyword that inserts ten pixels of horizontal padding around the widget within its cell. The stem asks for padding options, and padx is one of the two accepted grid padding parameters, alongside pady.

Why this answer

In Tkinter's grid geometry manager, external padding around a widget is set with the padx and pady options, so option D (padx=10) adds 10 pixels of horizontal padding and option E (pady=10) adds 10 pixels of vertical padding to the widget's cell. These are the standard grid() parameters for per-widget padding, e.g., widget.grid(row=0, column=0, padx=10, pady=10). Option A (margin=10) is not a recognized Tkinter geometry option, and option B (spacing=10) is not a valid grid() parameter either.

Option C (gap=10) is likewise not a Tkinter grid option; internal padding between widgets in a container is instead controlled by the container's padx/pady or by grid's ipadx/ipady for internal widget padding, not by a 'gap' keyword.

7
MCQhard

You are building a Tkinter GUI that includes a Canvas widget. You want to draw a rectangle and then later change its fill color without redrawing the entire canvas. Which method should you use to update the rectangle's fill color?

A.rectangle.fill('blue')
B.canvas.create_rectangle(..., fill='blue')
C.canvas.itemconfig(rectangle_id, fill='blue')
D.canvas.config(fill='blue')
AnswerC

The itemconfig method (or itemconfigure) allows you to modify the options of an existing canvas item by its ID. Passing the rectangle's ID and the new fill color updates only that item, leaving other canvas elements untouched. This is efficient and preserves the item's other properties. It is the correct way to dynamically change a canvas item's appearance after creation.

Why this answer

Canvas items are managed by the Canvas widget and are referenced by integer IDs. To change an item's options after creation, you use canvas.itemconfig with the item ID and the new option values. Recreating the item adds a new one, configuring the canvas itself does not affect items, and items are not Python objects with methods.

Thus, itemconfig is the correct method.

Exam trap

The trap here is assuming canvas items are objects with methods or that recreating them updates the original.

8
MCQhard

You are building a canvas-based drawing tool and need to detect when the user clicks on a specific rectangle item to select it, while other clicks should be ignored. Which canvas feature should you use?

A.Call itemconfigure() on the rectangle with an activefill option to detect selection.
B.Bind <Button-1> to the top-level window and use the focus() method to determine which item was clicked.
C.Use the canvas tag_bind() method to bind <Button-1> to the rectangle's tag or item id.
D.Bind a <Button-1> handler to the canvas and compare event coordinates against the rectangle's bounding box.
AnswerC

tag_bind() associates an event binding with a tag or a specific item id, so the callback fires only when the pointer interacts with that item. This leverages the canvas's built-in hit testing and respects overlapping items according to display order. It is the intended way to make individual canvas items interactive, and it automatically follows the item if it is moved, since the binding is tied to the item rather than to fixed coordinates.

Why this answer

Canvas items support their own event bindings through tag_bind(), which ties a callback to a tag or item id. When the user clicks, the canvas performs hit testing and invokes the binding only if the pointer is over a matching item, honoring stacking order for overlaps. This is more robust than comparing raw coordinates and automatically tracks items as they move or change, making it the correct choice for selecting individual shapes.

Exam trap

The trap here is assuming that a canvas-wide <Button-1> binding with manual coordinate checks is necessary, when tag_bind() already provides item-level hit testing.

9
MCQmedium

A Tkinter data-entry form uses an Entry widget for a numeric amount. Users report that pressing Enter in the Entry does nothing, and the value is only saved when they click a separate Save button. You want Enter to trigger the same save routine as the button, without duplicating logic. Which binding achieves this?

A.entry.bind('<KeyPress>', lambda event: save_amount())
B.entry.bind('<Enter>', lambda event: save_amount())
C.entry.bind('<FocusOut>', lambda event: save_amount())
D.entry.bind('<Return>', lambda event: save_amount())
AnswerD

The <Return> sequence corresponds to the Enter key on the main keyboard, and binding it on the Entry invokes the handler whenever that widget has focus. Using a lambda that calls the existing save_amount function reuses the same logic as the Save button, so there is no duplication. The event parameter is accepted and ignored, which is fine for a simple trigger.

Why this answer

The <Return> event sequence is the correct Tkinter binding for the Enter key on an Entry widget. Binding it to a small lambda that calls the existing save function reuses the button's logic and gives users the keyboard shortcut they expect. KeyPress is too broad, Enter refers to pointer entry, and FocusOut triggers on focus changes rather than the Enter key.

Exam trap

The trap here is confusing the <Enter> event, which fires when the mouse pointer enters a widget, with the <Return> event sequence generated by the Enter key.

10
MCQmedium

A Tkinter application has a main window containing a Text widget used as a log console. The application performs a long-running data import and must remain responsive, so the import runs in a background thread. The worker thread needs to append status lines to the Text widget. Which approach is correct?

A.Wrap each insert call in a threading.Lock shared with the main thread so only one thread touches the Text widget at a time.
B.Have the worker thread place messages on a queue.Queue, and have the main thread poll that queue periodically using the after method and perform the insert calls.
C.Call the Text widget's insert method directly from the worker thread, since Tkinter serializes widget access internally.
D.Call the root window's update_idletasks method from the worker thread before each insert so pending events are processed first.
AnswerB

The queue acts as the only shared object between threads, and the main thread retrieves messages through a scheduled after callback, so every widget operation occurs on the thread that owns the Tcl interpreter. This keeps the interface responsive because the main thread never blocks on the import, and it avoids the undefined behavior of cross-thread widget calls. It is the standard, safe pattern for Tkinter multithreading.

Why this answer

Tkinter widgets may only be manipulated from the thread that created the root window, so a background worker must not touch the Text widget directly. Passing messages through a queue and having the main thread drain it with an after-scheduled callback keeps all widget calls on the owning thread while the import proceeds in parallel. This preserves responsiveness and avoids interpreter corruption.

Exam trap

The trap here is believing that locks or internal serialization make Tkinter widget calls safe from any thread, when the real constraint is that only the thread owning the Tcl interpreter may drive widgets.

11
MCQhard

How do you access the value of a StringVar associated with an Entry widget?

A.var.retrieve()
B.var.content()
C.var.get()
D.var.value
AnswerC

Calling `get()` on the `StringVar` retrieves its current contents, which mirror the Entry widget's text because the two are bound together. This satisfies the stem's requirement to access the variable's value directly, rather than querying the widget itself via `Entry.get()`.

Why this answer

The get() method is used on the StringVar object to retrieve its current value.

12
MCQhard

You are developing a Tkinter application that uses multiple threads to perform background tasks. One thread updates a Label widget's text using its config method. Occasionally, the application crashes with a Tcl error about calling from a different thread. What is the correct approach to safely update the GUI from a background thread?

A.Use the after method to schedule the update on the main thread.
B.Directly call the widget's config method from the background thread; Tkinter handles thread safety internally.
C.Use a lock (threading.Lock) around the widget update to prevent concurrent access.
D.Call update_idletasks() before updating the widget from the background thread.
AnswerA

The after method can be used to schedule a function to run in the main event loop. By calling after from the background thread, you can pass a callback that performs the GUI update. This ensures the update occurs in the main thread, avoiding thread safety issues. This is the recommended approach for thread-safe GUI updates.

Why this answer

Tkinter is not thread-safe; all GUI updates must occur in the main thread. To safely update a widget from a background thread, you should use the after method to schedule a callback that performs the update. This callback runs in the main event loop.

Other approaches like using locks or update_idletasks do not address the fundamental thread safety issue. Direct calls from background threads are unsafe.

Exam trap

The trap here is assuming that Tkinter is thread-safe or that using locks can make it safe, but the only safe way is to schedule updates on the main thread.

13
MCQmedium

You are building a Tkinter application with a Button widget that should run a long-running calculation when clicked, but the GUI freezes until the calculation finishes. Which approach best keeps the interface responsive while performing the calculation?

A.Run the calculation in a separate thread and update the GUI using a thread-safe mechanism such as a queue polled by after().
B.Call update_idletasks() inside the calculation loop to refresh the window.
C.Call the calculation function directly inside the button's command callback.
D.Use the after() method with a delay of zero to schedule the calculation repeatedly.
AnswerA

Tkinter is not thread-safe, so GUI updates must happen on the main thread. Running the heavy calculation in a worker thread keeps the event loop free to redraw and respond to input. The worker communicates results through a queue, and the main thread polls that queue using after(), performing widget updates safely on the main thread. This combination preserves responsiveness without violating Tkinter's threading constraints.

Why this answer

Tkinter widgets must be manipulated from the thread that created the Tk instance, which is normally the main thread running mainloop(). Performing a long computation in a button callback monopolizes that thread, freezing the interface. The reliable pattern is to execute the computation in a worker thread and pass results back through a thread-safe queue that the main thread inspects with after().

This keeps the event loop cycling and the GUI responsive.

Exam trap

The trap here is assuming that calling update_idletasks() or after() with a zero delay makes long-running work non-blocking, when in fact both still execute on the main event loop thread.

14
MCQeasy

You need to add a label that displays static text in your GUI. Which widget is most appropriate for this purpose?

A.tk.Message()
B.tk.Entry()
C.tk.Display()
D.tk.Label()
E.tk.Text()
AnswerD

tk.Label() renders static, non-editable text and accepts no user input, matching the requirement for a display-only label. Unlike Entry or Text, it exposes no editing or selection behaviour, so it is the minimal widget satisfying the static-text constraint.

Why this answer

tk.Label() is the canonical Tkinter widget for displaying static, non-editable text (or images) in a GUI. It supports options like text, font, fg, bg, and anchor, and is designed specifically for read-only display. For multi-line static text, tk.Message() is a variant, but tk.Label() is the general-purpose choice.

Exam trap

PCPP1 often tests the distinction between Label (static display) and Entry/Text (editable input) — candidates may confuse Message with Label or pick a fabricated widget like Display.

How to eliminate wrong answers

Option A is wrong because tk.Message() is a specialized widget for multi-line text that wraps automatically — it is less flexible than Label and not the general-purpose choice for static text. Option B is wrong because tk.Entry() is a single-line editable input field, not a display widget. Option C is wrong because tk.Display() does not exist in Tkinter — it is a fabricated widget name.

Option E is wrong because tk.Text() is a multi-line editable text area, not a static label.

15
MCQeasy

You are prototyping a Tkinter application and want a single-line input field where users can type a search term. The field should also show a placeholder-like behavior by pre-filling the text 'Search...' when the window opens. Which widget and option combination achieves this most directly?

A.An Entry widget with a StringVar whose initial value is 'Search...' and passed via the `textvariable` option.
B.A Text widget with `height=1` and the initial string passed as the first positional argument.
C.A Spinbox widget with `values=('Search...',)` and `state='readonly'` so the placeholder cannot be modified.
D.A Label widget with `textvariable` bound to a StringVar set to 'Search...' and made editable via `state=tk.NORMAL`.
AnswerA

Entry is the standard single-line input widget. Binding a StringVar initialized to 'Search...' through `textvariable` pre-fills the field and keeps the value synchronized for later reading. This is the most direct way to seed initial text while retaining two-way data binding, and it matches the single-line search field requirement exactly.

Why this answer

An Entry widget is the canonical single-line text input in Tkinter. Pairing it with a StringVar initialized to the placeholder text and connected via `textvariable` gives both an initial visible value and a live binding that the application can read or update. This directly satisfies the requirement of a pre-filled, editable search field without extra workarounds.

Exam trap

The trap here is reaching for Text or Label when the requirement is a single-line editable field with initial content, which is exactly Entry's role.

16
MCQmedium

You wish to group several widgets together within a frame. Which widget acts as a container for this purpose?

A.tk.Group()
B.tk.Box()
C.tk.Container()
D.tk.Frame()
AnswerD

'tk.Frame()' creates a rectangular container widget that groups and positions child widgets, and can itself be placed inside a window or another frame. This directly satisfies the stem's requirement for a widget acting as a container.

Why this answer

The Frame widget is specifically designed as a container to group other widgets.

17
MCQeasy

You are creating a Tkinter application with a Canvas widget. You draw a circle using create_oval and assign it the tag 'ball'. Later, you want to move the circle 10 pixels to the right and 5 pixels down. Which Canvas method should you use?

A.canvas.coords('ball', 10, 5)
B.canvas.translate('ball', 10, 5)
C.canvas.move('ball', 10, 5)
D.canvas.moveto('ball', 10, 5)
AnswerC

The move method takes a tag or item ID and delta x and delta y values, and moves the item(s) by that amount. Using the tag 'ball' moves all items with that tag, which in this case is the circle, by 10 pixels right and 5 pixels down, exactly as required.

Why this answer

The Canvas.move method is designed to shift items by a relative offset. It accepts a tag or item ID and delta x and delta y values. The other methods either set absolute coordinates, do not exist, or are from different libraries.

Thus, move is the correct choice for moving the circle by (10,5).

Exam trap

The trap here is confusing move with coords, or assuming a moveto method exists similar to other GUI frameworks.

18
Multi-Selectmedium

You are designing a Tkinter application that uses a ttk.Treeview to display a table of records. You need to configure the widget so that users can select multiple non-contiguous rows and so that the first column shows a tree-style expander control. Which two actions must you perform? (Choose two.)

Select 2 answers
A.Call tree.heading('#0', text='Name') to set the label of the tree column.
B.Set the show option to 'tree headings' or include 'tree' in the show tuple.
C.Set the height option to a value greater than the number of rows.
D.Call tree.column('#0', stretch=True) to make the tree column resize with the widget.
E.Set the selectmode option to 'extended' when creating the Treeview.
AnswersB, E

The show option determines which parts of the Treeview are displayed. Including 'tree' displays the tree column with expander controls, while 'headings' shows the column headers. Using 'tree headings' displays both, so the first column can act as an expandable tree node, matching the requirement.

Why this answer

Multi-selection in a Treeview is governed by selectmode, which must be 'extended' to allow non-contiguous picks. The tree-style expander in the first column is controlled by the show option: including 'tree' (for example, 'tree headings') displays the tree column with expander controls. Heading text, height, and stretch are unrelated to these two requirements.

Exam trap

The trap here is thinking that setting a heading or column option enables the tree expander, when only the show option controls whether the tree column is rendered.

19
MCQeasy

You are creating a simple Tkinter application and notice that your window does not appear on the screen after calling the Tk() constructor. Which method must be called to start the event loop?

A.root.show()
B.root.render()
C.root.mainloop()
D.root.run()
AnswerC

Tk() only constructs the root window; nothing is drawn or processed until the event loop runs. Calling root.mainloop() hands control to Tk's event dispatcher, satisfying the stem's requirement to start the event loop so the window appears and responds.

Why this answer

The mainloop() method is required to start the Tkinter event loop, which listens for events and updates the display.

20
MCQmedium

You have a Checkbutton and you need to track its state. What is the recommended way to associate a variable with the Checkbutton?

A.Use the 'onvalue' parameter.
B.Pass a BooleanVar object to the 'variable' parameter.
C.Use the state attribute directly.
D.Use the 'command' parameter to set a global flag.
AnswerB

Tkinter's Checkbutton writes its on/off state into a shared control variable, so passing a BooleanVar to the 'variable' parameter lets you read or set the tick state directly through that object rather than polling widget internals.

Why this answer

A BooleanVar or IntVar should be passed to the 'variable' parameter of the Checkbutton.

21
MCQhard

A colleague built a Tkinter form where every Entry widget uses `pack()` in the same frame. They now need the labels to sit in a single column with the entries aligned in the next column and the whole form centered. They ask you to recommend the smallest structural change that makes this alignment reliable. What should you suggest?

A.Replace `pack()` with `grid()` inside a dedicated Frame, assigning labels and entries to the same row with different column indexes, then pack that Frame into the parent.
B.Keep `pack()` but add `side=tk.LEFT` to every label and `side=tk.RIGHT` to every entry so they form two implicit columns.
C.Use `pack()` for the labels and `grid()` for the entries in the same container, relying on Tkinter to merge both managers automatically.
D.Switch each Entry to `place()` and hard-code its x and y coordinates based on the current window size.
AnswerA

The grid geometry manager is designed for row-and-column alignment. Placing the labels in column 0 and entries in column 1 of the same row guarantees vertical alignment regardless of text length or font. Wrapping that grid inside its own Frame and packing the Frame lets you center the whole form in the parent, which is the minimal, idiomatic change for this requirement.

Why this answer

Grid is the correct tool for two-column alignment because it assigns widgets to explicit row and column cells, keeping labels and entries aligned regardless of content width. Wrapping the grid in its own Frame and packing that Frame into the parent is the smallest structural change that both aligns the fields and centers the form, without rewriting the entire window layout.

Exam trap

The trap here is thinking pack() can emulate columns through side options, when only grid() provides true row-and-column cell alignment.

22
MCQhard

When using the grid layout manager, which option allows a column to grow when the window is resized?

A.root.grid_grow(column=0, weight=1)
B.root.columnconfigure(0, weight=1)
C.root.grid_column(0, resizable=True)
D.root.set_grid(0, expand=True)
AnswerB

Assigning a non-zero weight to column 0 via columnconfigure makes Tkinter distribute any surplus width to that column when the window grows, satisfying the resize constraint. Weight defaults to 0, so columns stay fixed without it; weight=1 grants the column proportional claim on extra space.

Why this answer

The columnconfigure() method is used to set the weight of a column, allowing it to expand.

23
Multi-Selecthard

You are reviewing a Tkinter application that uses ttk widgets and a Canvas to draw a seating chart. The chart must redraw when the window is resized, and a toolbar above it must stay a fixed height. Which two techniques correctly contribute to a layout where the Canvas expands and the toolbar does not? (Choose two.)

Select 2 answers
A.Set canvas.configure(width=800, height=600) and bind the toplevel's <Configure> event to call canvas.configure with the new toplevel size.
B.Call canvas.pack(expand=True, fill='both') and toolbar.pack(side='top') in the same parent, relying on pack to keep the toolbar fixed.
C.Set the toolbar's grid row weight to 1 and the Canvas row weight to 0, then call canvas.update_idletasks() after each resize.
D.Place the toolbar and Canvas in the same container with grid(), give the toolbar row weight=0 and the Canvas row weight=1, and set sticky='nsew' on the Canvas so it adheres to all cell edges.
E.Bind the Canvas <Configure> event to a handler that reads event.width and event.height and redraws the chart using those dimensions.
AnswersD, E

Row weights control how surplus vertical space is distributed by grid(). A weight of zero keeps the toolbar row at its natural height, while a weight of one lets the Canvas row absorb all extra space. The sticky='nsew' option makes the Canvas fill the entire cell rather than centering at its requested size, which is required for the chart to use the available area.

Why this answer

A responsive chart needs both correct space allocation and a redraw trigger. Weighted grid rows with sticky='nsew' ensure the Canvas receives the surplus area while the toolbar keeps its natural height, and a <Configure> binding on the Canvas supplies the new dimensions for redrawing. The other options either mix incompatible geometry managers, hard-code sizes, or invert the weights.

Exam trap

The trap here is focusing only on making the Canvas expand while forgetting that the drawing itself must be regenerated from the Canvas's own <Configure> event to follow the new size.

24
MCQhard

You are designing a Tkinter application with a Listbox widget that displays multiple items. You want to allow the user to select multiple non-contiguous items (e.g., by holding Ctrl and clicking). Which configuration option of the Listbox should you set, and to what value?

A.selectmode='multiple'
B.selectmode='browse'
C.selectmode='single'
D.selectmode='extended'
AnswerD

Setting selectmode to 'extended' enables the standard multi-selection behavior where users can select multiple items using Ctrl+click for non-contiguous items or Shift+click for ranges. This is the default mode for Listbox and matches typical desktop application behavior. It provides the most intuitive user experience for multiple selections.

Why this answer

The Listbox widget's selectmode option controls how many items can be selected and how. The 'extended' mode allows multiple selections using Ctrl+click for non-contiguous items and Shift+click for ranges, which is the standard behavior. The 'multiple' mode allows multiple selections but with a toggle mechanism, not requiring Ctrl. 'single' and 'browse' restrict to one selection.

Exam trap

The trap here is confusing 'multiple' and 'extended' select modes, as both allow multiple selections but with different interaction models.

25
MCQhard

You are writing a Tkinter dialog that must react to a user pressing the Escape key at any time, even when focus is inside an Entry widget. You have a function named on_cancel. Which binding correctly achieves this?

A.root.bind_class('Entry', '<Escape>', on_cancel)
B.root.bind_all('<Escape>', on_cancel)
C.entry.bind('<Escape>', on_cancel)
D.root.bind('<Escape>', on_cancel, add='+')
AnswerB

bind_all registers the handler at the application level, so the binding fires regardless of which widget currently has focus. This is the correct way to implement a global keyboard shortcut such as Escape to cancel a dialog, because it applies to every widget in the application without needing to bind each one individually.

Why this answer

A global cancel shortcut must be registered at the application level. bind_all places the handler in the application-wide binding table so it triggers no matter which widget has focus. Widget-level and class-level bindings are scoped to specific widgets or widget classes and therefore miss events when focus is elsewhere, which is why they cannot satisfy the scenario.

Exam trap

The trap here is confusing bind_class with bind_all: bind_class targets a widget class, while bind_all applies to the entire application regardless of focus.

26
MCQmedium

You are creating a Tkinter application with a menu bar. You want to add a keyboard shortcut (accelerator) to a menu item so that pressing Ctrl+S triggers the save action. Which option of the add_command method should you use to display the shortcut text, and what additional step is required to make the shortcut functional?

A.Use the accelerator option to display 'Ctrl+S', and the shortcut will automatically be functional without additional code.
B.Use the accelerator option to display 'Ctrl+S', and bind the keystroke to the save function using the bind method on the root window.
C.Use the command option to specify both the function and the shortcut, e.g., command=(save, 'Ctrl+S').
D.Use the underline option to set the shortcut key, and bind it using the bind method.
AnswerB

The accelerator option only displays the shortcut text next to the menu item; it does not create the binding. To make the shortcut work, you must explicitly bind the key sequence (e.g., '<Control-s>') to the save function using bind on a widget, typically the root window. This two-step process is necessary because Tkinter does not automatically associate the accelerator text with the binding.

Why this answer

In Tkinter, the accelerator option of a menu item only displays the shortcut text; it does not create a key binding. To make the shortcut functional, you must explicitly bind the key sequence to the desired function using the bind method, typically on the root window. The underline option is for mnemonics, and the command option only sets the callback for menu selection.

Exam trap

The trap here is assuming that setting the accelerator option automatically enables the keyboard shortcut.

27
MCQmedium

You have a list of options and want the user to select one using a dropdown menu. Which widget should you use?

A.tk.ComboBox()
B.tk.Select()
C.tk.Dropdown()
D.tk.OptionMenu()
AnswerD

tk.OptionMenu() binds a Tk variable to a menubutton displaying the current selection, letting the user pick exactly one value from a fixed list. This directly satisfies the stem's single-selection dropdown constraint, unlike Checkbutton or Listbox, which permit multiple selections or expose no collapsed menu.

Why this answer

tk.OptionMenu() is the correct widget because it is specifically designed to present a fixed set of options as a dropdown menu in Tkinter. It is a subclass of Menubutton that displays the currently selected option and, when clicked, reveals a menu of choices. The user can select exactly one option, and the widget automatically updates the displayed text to reflect the selection.

Exam trap

PCPP1 often tests the difference between classic Tkinter widgets and themed ttk widgets, and candidates may mistakenly choose ttk.Combobox or assume a widget named Dropdown exists.

How to eliminate wrong answers

Option A is wrong because tk.ComboBox() does not exist in standard Tkinter; the closest widget is ttk.Combobox, which is part of the themed ttk module and not a direct tk method. Option B is wrong because tk.Select() is not a Tkinter widget at all; there is no such class for creating dropdowns. Option C is wrong because tk.Dropdown() is not a Tkinter widget; dropdown functionality is provided by OptionMenu or ttk.Combobox, not a class named Dropdown.

28
Multi-Selectmedium

Which THREE of the following are valid parameters for the pack() layout manager?

Select 3 answers
A.row
B.expand
C.column
D.side
E.fill
AnswersB, D, E

The `expand` parameter accepts a Boolean value that allocates surplus space to a widget when its parent is resized, stretching it along the packing direction. This satisfies the stem's requirement for a genuine `pack()` argument, unlike geometry options belonging to `grid()` or `place()`.

Why this answer

The pack() geometry manager accepts the expand option (B), a Boolean that tells pack to allocate extra space in the parent container to the widget, letting it grow when the window is resized. It also accepts the side option (D), which specifies the edge against which the widget is packed — values are TOP (default), BOTTOM, LEFT, and RIGHT. The fill option (E) is valid as well, controlling whether the widget stretches to fill its allocated parcel; its values are NONE, X, Y, or BOTH.

Options A (row) and C (column) are not pack() parameters — they belong to the grid() geometry manager, where row and column specify the cell coordinates for a widget.

29
MCQmedium

You are developing a Tkinter application with a top-level window that contains a Frame widget. Inside the Frame, you place three Button widgets using grid(). Later, you need to add a fourth Button that should span the full width of the Frame, below the existing three. Which grid() configuration should you apply to the new Button?

A.button.grid(row=3, column=0, columnspan=3, sticky='ns')
B.button.grid(row=3, column=0, columnspan=3, sticky='nsew')
C.button.grid(row=0, column=3, rowspan=3, sticky='ns')
D.button.grid(row=3, column=0, columnspan=3, sticky='ew')
AnswerD

Using row=3 places the button in the next available row, column=0 starts at the first column, columnspan=3 makes it occupy all three columns, and sticky='ew' stretches it horizontally to fill the frame width, achieving the desired full-width span.

Why this answer

To place a widget below existing grid-managed widgets and have it span the full width, you must specify the next row, start at column 0, set columnspan to the number of columns to cover, and use sticky='ew' to stretch horizontally. The other options either misplace the widget or stretch it in the wrong direction.

Exam trap

The trap here is confusing rowspan with columnspan or using sticky='nsew' when only horizontal expansion is needed.

30
MCQmedium

Which widget is most appropriate for displaying a list of selectable items?

A.tk.Checkbutton()
B.tk.Listbox()
C.tk.OptionMenu()
D.tk.Menu()
AnswerB

tk.Listbox() renders a scrollable list of text items and natively supports single or extended selection, satisfying the requirement for selectable items. Unlike read-only display widgets, it tracks a selection index and emits virtual events, making it the direct fit for choosing from a list.

Why this answer

The Listbox widget is intended for displaying a list of strings that the user can select.

31
MCQeasy

A desktop tool built with Tkinter needs a list of departments shown as mutually exclusive radio buttons. When the user selects a department, the underlying model object's department attribute must update immediately, and the code must read the selection later without iterating over every radio button. Which Tkinter mechanism best satisfies these requirements?

A.Use a ttk.Combobox and call get() on it whenever the model is saved to the database.
B.Give each Radiobutton its own BooleanVar and inspect all of them with cget when the model needs the current department.
C.Use a Listbox configured with selectmode='browse' and read its curselection() to determine the chosen department.
D.Create an IntVar or StringVar, pass it as the variable option to every Radiobutton in the group, and read or trace that variable when the model needs updating.
AnswerD

Radiobuttons sharing a single Tkinter variable form one mutually exclusive group; selecting one sets the variable to that button's value and clears the others automatically. Binding a trace_add callback on the variable pushes changes straight into the model, and reading the variable later requires no widget iteration. This is the idiomatic Tkinter way to keep selection state and application data synchronized.

Why this answer

A shared Tkinter variable is the mechanism that ties a group of Radiobuttons together and makes their selection readable as a single value. Because the variable can be traced, the model updates the moment the user clicks, and later reads need only the variable rather than a loop over widgets. Separate variables, Listboxes, and Comboboxes all fail at least one stated requirement.

Exam trap

The trap here is assuming that each Radiobutton needs its own variable, when in fact a single shared variable is what creates the mutually exclusive group and the convenient read point.

32
Multi-Selecteasy

Which TWO of the following are valid geometry managers in Tkinter?

Select 2 answers
A.pack
B.block
C.align
D.flow
E.grid
AnswersA, E

'pack' is a genuine Tkinter geometry manager, arranging widgets in blocks against the parent's edges before the next widget. It satisfies the stem by being one of the three valid managers alongside 'grid' and 'place'.

Why this answer

Option A, pack, is a valid Tkinter geometry manager that organizes widgets by packing them against the edges of their parent container in the order they are added. Option E, grid, is also a valid Tkinter geometry manager that places widgets in a two-dimensional table of rows and columns using row and column indices. The other options do not belong: block, align, and flow are not Tkinter geometry managers; Tkinter's third standard geometry manager is place, which is not listed here.

33
MCQhard

A Tkinter application uses a Canvas to draw a seating chart. Each seat is a rectangle created with create_rectangle, and seats are grouped by section. When a section is selected, every seat in it must change fill color, and some seats must later be moved to a new position. Which strategy best supports efficient grouped updates while keeping individual seats addressable?

A.Delete all rectangles in the section and recreate them with the new color and position whenever a section changes.
B.Assign a unique tag to each seat's rectangle and use the tag to call itemconfig on all seats in the section, and use coords or move to reposition individual seats.
C.Place each seat rectangle inside its own Frame widget and change the Frame background color, relying on the canvas window items to reflect the change.
D.Store each rectangle's item id in a dictionary and iterate over the section, calling itemconfig and coords on each id individually.
AnswerB

Canvas tags let a single itemconfig call recolor every item sharing the tag, so a section update is one operation rather than a loop of per-item calls. Each seat can still carry its own unique tag as well, allowing precise repositioning with coords or move. This design gives both bulk section updates and individual addressability, exactly matching the requirement of grouped recoloring plus selective movement.

Why this answer

Canvas tags are the intended mechanism for applying an operation to many items at once: itemconfig with a tag recolors every matching item in a single call, and each seat can also carry a unique tag for precise coords or move operations. This yields efficient section-wide updates while preserving individual addressability, unlike per-item loops or destructive recreation.

Exam trap

The trap here is treating tags as mere labels for lookups, when their real power is that itemconfig, move, and delete accept a tag and act on every matching item at once.

34
MCQmedium

You are maintaining a Tkinter inventory application where users type quantities into an Entry widget. A colleague reports that the application accepts "12.5" for an item that must be a whole number, and invalid keystrokes are only caught after the user clicks Save. You must reject non-numeric input as it is typed, while still allowing a normal editing experience. Which mechanism should you register on the Entry widget?

A.A command callback passed to the Entry widget's validatecommand option, with validate set to "key".
B.A call to the Entry widget's config method with the state option set to "readonly" while the user is typing.
C.A trace callback attached to a StringVar linked to the Entry widget, raising an exception whenever the new value is not an integer.
D.A binding for the <Return> event that inspects the Entry contents and shows a messagebox when the value is not an integer.
AnswerA

Registering a validation callback through validatecommand with validate="key" makes Tkinter invoke the callback on each keystroke, before the character is inserted. Returning False from the callback rejects the edit immediately, so letters or decimal points never appear in the field. This matches the requirement of rejecting invalid input as it is typed rather than only at save time, and it preserves normal cursor and editing behavior.

Why this answer

Tkinter's Entry validation framework invokes a registered callback at defined moments, and validate="key" triggers it on every keystroke before the change is applied. Returning False from that callback cancels the edit, so non-integer characters are rejected immediately while legitimate editing continues to work. This is the only listed approach that prevents bad input from ever reaching the widget, matching the stated requirement.

Exam trap

The trap here is assuming that any callback reacting to typed input can block it, when only the validation callback registered with validatecommand can veto an edit before it happens.

35
Multi-Selecthard

You are building a Tkinter desktop application with a menu bar. Users report two problems: keyboard shortcuts such as Ctrl+S do not trigger the Save command when focus is inside a Text widget, and mnemonic underlines on the File menu are missing. You must correct the menu configuration. Which two changes should you make? (Choose two.)

Select 2 answers
A.Configure the menu entry with state="normal" so keyboard traversal is enabled for the File menu.
B.Bind the <Control-s> event to the save handler on the root window or on the widget that holds focus, in addition to adding the menu entry.
C.Set tearoff=0 on the menubar so the File menu can be detached and the underline becomes visible.
D.Pass accelerator="Ctrl+S" to the Save menu entry so the shortcut text is displayed next to the command.
E.Set underline=0 on the File cascade menu entry so the first character receives a mnemonic underline.
AnswersB, E

Menu accelerators in Tkinter are cosmetic: the displayed text does not install a binding. To make Ctrl+S actually invoke the handler, you must bind the <Control-s> event, typically on the root window or the focused widget, and route it to the save function. This directly addresses the missing behavior users reported when focus is inside the Text widget.

Why this answer

In Tkinter, the accelerator option only displays shortcut text and does not install a binding, so making Ctrl+S work requires an explicit binding of <Control-s> to the handler. Separately, mnemonic underlines come from the underline option, which names the character index to underline on the menu label. Applying those two settings fixes the reported shortcut and underline problems.

Exam trap

The trap here is assuming that specifying an accelerator automatically creates the keyboard shortcut, when in Tkinter it only renders the label text and a real binding is still required.

36
MCQmedium

You are creating a dialog window in a Tkinter application that must block interaction with the main window until the user closes it, and must return a value to the caller. Which approach correctly implements this behavior?

A.Use the messagebox.askyesno() function, since it returns a value and is always modal.
B.Set the Toplevel's transient() option to True and call update() in a loop until the user closes it.
C.Create a Toplevel, call grab_set() on it, use wait_window() to wait until it is destroyed, then read the stored result.
D.Create a Toplevel, call its mainloop(), and read a global variable after it returns.
AnswerC

A Toplevel with grab_set() becomes modal, routing input events to it and preventing interaction with other windows. wait_window() then blocks the calling code until the dialog is destroyed, without starting a competing mainloop. Storing the result on the dialog instance before destroying it lets the caller read the value afterward. This is the standard, reliable pattern for modal dialogs in Tkinter.

Why this answer

A modal dialog must prevent input to other application windows and block the caller until dismissed. Creating a Toplevel, calling grab_set() to capture input, and then calling wait_window() achieves both: the grab routes events to the dialog, and wait_window() suspends the caller until the dialog is destroyed. Storing the result on the dialog instance before destruction lets the caller retrieve it after wait_window() returns.

Exam trap

The trap here is assuming that transient() alone creates modality or that calling mainloop() on a Toplevel is the proper way to wait for a dialog.

37
Multi-Selecthard

Which THREE of the following widgets are part of the 'ttk' (Themed Tkinter) module?

Select 3 answers
A.ttk.Entry
B.ttk.Button
C.ttk.Label
D.ttk.Window
E.ttk.Canvas
AnswersA, B, C

ttk.Entry is the themed counterpart of tkinter.Entry, wrapping the native Tk themed widget set. Its presence in the ttk module satisfies the stem's criterion of identifying widgets belonging to Themed Tkinter, distinguishing it from the classic tkinter.Entry class.

Why this answer

Options A, B, and C are correct because ttk.Entry, ttk.Button, and ttk.Label are all genuine themed widgets provided by the tkinter.ttk module, replacing their classic Tkinter counterparts (tkinter.Entry, tkinter.Button, tkinter.Label) with native-looking, theme-aware versions. ttk.Entry provides a themed single-line text input, ttk.Button provides a themed push button, and ttk.Label provides a themed non-editable text or image display. Option D is incorrect because there is no ttk.Window widget; top-level windows are created with tkinter.Tk or tkinter.Toplevel, and ttk offers no window class. Option E is incorrect because ttk.Canvas does not exist; the canvas widget is only available as tkinter.Canvas in the classic Tk widget set, not in the themed ttk module.

38
MCQeasy

Which module must be imported to utilize Tkinter in a Python script?

A.import tkinter
B.import gui
C.from python import gui
D.import tk
AnswerA

Importing `tkinter` binds the standard-library GUI package directly, satisfying the stem's requirement to utilise Tkinter. Unlike third-party alternatives such as PyQt, it ships with CPython, so no separate installation is needed. The module exposes widgets, geometry managers and the main event loop, letting the script construct and run a window immediately.

Why this answer

Tkinter is Python's standard GUI library, and it is imported with the statement 'import tkinter' (lowercase). This is the correct module name in Python 3; in Python 2 it was 'Tkinter' with a capital T, but Python 3 standardized it to lowercase.

Exam trap

The trap is the Python 2 vs. Python 3 naming difference — candidates who learned on Python 2 may pick 'Tkinter' (capital T), but the exam expects the Python 3 lowercase 'tkinter'.

How to eliminate wrong answers

Option B is wrong because there is no standard module named 'gui' in Python — it is a fabricated name. Option C is wrong because 'from python import gui' is syntactically and semantically invalid; 'python' is not a module, and 'gui' is not a submodule. Option D is wrong because 'tk' is not the module name — while there is a 'tkinter.ttk' submodule for themed widgets, the top-level module is 'tkinter', not 'tk'.

39
MCQeasy

You have a Button widget and want to trigger a function named 'process_data' when the user clicks it. Which is the standard way to associate the function with the button?

A.button = Button(root, event=process_data)
B.button.bind('<Button-1>', process_data)
C.button = Button(root, command=process_data)
D.button.set_action(process_data)
AnswerC

Passing the function object directly to the `command` parameter binds `process_data` as the button's callback, so Tkinter invokes it on each click without arguments. This satisfies the stem's requirement for the standard association method, unlike `bind()`, which links events rather than the widget's built-in command hook.

Why this answer

The 'command' parameter is the standard way to bind a callback function to a button click event.

40
MCQeasy

You are placing several widgets in a window using the grid() geometry manager and want a widget to span multiple columns in the same row. Which grid() option accomplishes this?

A.ipadx
B.rowspan
C.columnspan
D.sticky
AnswerC

columnspan tells grid() that the widget should occupy the specified number of adjacent columns starting at its column index. Setting columnspan=3, for example, makes the widget stretch across three columns in its row. This is exactly the option needed to have a widget span multiple columns, and it works together with sticky to control how the widget fills the spanned area.

Why this answer

In grid(), the columnspan option specifies how many columns a widget should occupy, starting from its column index. This is the mechanism for horizontal spanning within a row. rowspan handles vertical spanning, sticky controls alignment and stretching inside the cell, and ipadx adds internal padding. Combining columnspan with sticky lets a widget both cover several columns and fill the resulting space as desired.

Exam trap

The trap here is confusing columnspan with sticky or ipadx, which change alignment or padding but never alter how many grid cells the widget occupies.

41
MCQmedium

You are building a Tkinter application with a menu bar. You want to add a 'File' menu with an 'Exit' item that terminates the application when selected. Which command should you associate with the 'Exit' menu item to properly close the application?

A.sys.exit
B.root.quit
C.root.end
D.root.destroy
AnswerD

Calling root.destroy() terminates the Tkinter application by destroying the main window and ending the mainloop. It is the standard way to exit a Tkinter app cleanly. Associating this method with the menu item will close the application when the user selects 'Exit'.

Why this answer

To properly close a Tkinter application from a menu item, you should call the destroy method on the root window. This destroys all widgets and exits the mainloop. The quit method only stops the mainloop, and sys.exit may not clean up GUI resources.

There is no end method.

Exam trap

The trap here is thinking that quit or sys.exit will fully close the application, when destroy is the correct method for a clean exit.

42
MCQeasy

You are creating a Tkinter GUI with a Canvas widget to draw a simple chart. You need to draw a filled blue rectangle from (50, 50) to (150, 100). Which Canvas method call achieves this?

A.canvas.create_rectangle(50, 50, 150, 100, fill='blue')
B.canvas.create_polygon(50, 50, 150, 100, fill='blue')
C.canvas.create_oval(50, 50, 150, 100, fill='blue')
D.canvas.create_line(50, 50, 150, 100, fill='blue', width=50)
AnswerA

create_rectangle accepts the two corner coordinates and an optional fill colour, so this call draws a rectangle with a blue interior exactly between the specified points. The Canvas widget's coordinate system places (0,0) at the top-left, so the shape appears in the expected location, satisfying the requirement.

Why this answer

The Canvas widget offers dedicated factory methods for common shapes. create_rectangle takes two coordinate pairs that define the top-left and bottom-right corners and accepts a fill option for the interior colour. Using the correct method ensures the shape is actually a rectangle rather than a degenerate polygon, a thick line, or an ellipse.

Exam trap

The trap here is assuming that any shape method with the same coordinates will produce a rectangle, when create_polygon needs four points and create_oval produces an ellipse.

43
MCQmedium

You maintain a Tkinter inventory dashboard whose main window contains a large frame with a Treeview listing warehouse items. Operators complain that when they maximize the window, the Treeview stays at its original size and leaves a large empty gray area. The frame is already managed with grid() and the Treeview is placed inside that frame with pack(). Which single change most directly makes the Treeview grow with the frame when the window is resized?

A.Call tree.config(width=200, height=50) so the Treeview requests a larger size whenever the window is maximized.
B.Call tree.pack(fill='both', expand=True) and configure the frame's row and column weights with frame.grid_rowconfigure(0, weight=1) and frame.grid_columnconfigure(0, weight=1).
C.Replace pack() with place() and use relwidth=1, relheight=1 so the Treeview always occupies the whole frame.
D.Set the frame's propagate(False) method and assign explicit pixel dimensions to the Treeview's width and height attributes.
AnswerB

This is the standard Tkinter recipe for a Treeview that tracks its container: pack(fill='both', expand=True) lets the widget claim extra space inside its parent frame, while grid_rowconfigure and grid_columnconfigure with weight=1 make the frame's internal cell distribute surplus space to the Treeview's row and column. Without the weight settings, the frame keeps the child at its requested size even when the frame itself grows.

Why this answer

A Treeview that must follow its parent needs two cooperating mechanisms: the geometry manager inside the frame must allow expansion, and the frame must be told to give surplus space to the cell containing the Treeview. Combining pack(fill='both', expand=True) with weighted grid rows and columns satisfies both conditions, which is why this is the canonical Tkinter pattern for resizable data tables.

Exam trap

The trap here is assuming that a single fill or expand argument is enough, when Tkinter also requires the parent's row and column weights to be configured before surplus space is actually distributed.

44
MCQhard

You are building a Tkinter application that uses a ttk.Treeview to display a list of employees. Each employee has an ID, name, and department. You want to display the data in columns with headings, and you need the ID column to be hidden. Which approach correctly configures the Treeview to achieve this?

A.Set the Treeview's 'columns' attribute to a list that omits the ID column, and insert items with values that exclude the ID.
B.Set the Treeview's 'show' option to 'tree headings' and set the ID column's width to 0.
C.Use the 'column' method to set the ID column's 'minwidth' to 0 and 'stretch' to False.
D.Set the Treeview's 'show' option to 'headings' and set the 'displaycolumns' attribute to a tuple excluding the ID column.
AnswerD

Setting show='headings' hides the tree column (the first column) and displays only the headings. The displaycolumns attribute specifies which columns are visible; excluding the ID column hides it while keeping the data accessible via item values. This is the correct way to hide a specific column.

Why this answer

The Treeview widget's displaycolumns attribute controls which columns are visible, and show='headings' hides the tree column. By setting displaycolumns to exclude the ID column, you hide it while retaining the data in the item values. The other options either do not hide the column or remove the data entirely.

Exam trap

The trap here is assuming that setting a column's width to zero or removing it from the columns list hides it, when actually displaycolumns is the correct attribute.

45
MCQmedium

In a Tkinter grid layout, you want a button to span across two columns. Which parameter should you use?

A.columnspan=2
B.span_cols=2
C.merge=2
D.cols=2
AnswerA

columnspan=2 instructs Tkinter's grid geometry manager to allocate two adjacent column cells to the widget, satisfying the stem's requirement that the button span two columns. The parameter is passed directly to grid(), and Tkinter merges the specified cells horizontally without altering other widgets' placements.

Why this answer

The columnspan parameter in the grid() method manager allows a widget to occupy multiple columns.

46
MCQeasy

What is the correct way to specify the title of a Tkinter window?

A.root.set_title('My App')
B.root.title('My App')
C.root.name = 'My App'
D.root.set_header('My App')
AnswerB

The Tk root window exposes title() as its method for setting the caption shown in the window manager's title bar, so root.title('My App') sets it directly. Assigning to a title attribute would not update the displayed caption.

Why this answer

Tkinter's Tk and Toplevel widget classes expose the title() method, which is the canonical API for setting the window manager caption. Calling root.title('My App') sets the WM_NAME property on the underlying X11/Win32 window, which the OS window manager renders in the title bar. There is no set_title() method on Tkinter widgets, so option A would raise an AttributeError at runtime.

Exam trap

The trap here is that candidates familiar with other GUI frameworks (Qt's setWindowTitle, Java Swing's setTitle, wxPython's SetTitle) assume Tkinter follows the same set_* naming convention, but Tkinter uses the terse title() method instead.

How to eliminate wrong answers

Option A is wrong because Tkinter widgets do not expose a set_title() method; the correct API is title(), and calling set_title() raises AttributeError. Option C is wrong because assigning root.name = 'My App' merely creates an arbitrary Python instance attribute on the Tk object and has no effect on the window manager caption. Option D is wrong because set_header() is not a Tkinter method at all — it does not exist on Tk, Toplevel, or any widget class, so it would raise AttributeError.

47
Multi-Selectmedium

Which THREE of the following are valid ways to configure a widget's appearance after it has been created?

Select 3 answers
A.widget['bg'] = 'blue'
B.widget.config(bg='blue')
C.widget.configure(bg='blue')
D.widget.set_bg('blue')
E.widget.style = 'blue'
AnswersA, B, C

Assigning to `widget['bg']` uses Tkinter's item-configuration protocol, routing the value to the widget's `configure()` method for the `bg` option. This mutates the existing widget's background colour in place, satisfying the stem's requirement that appearance be changed after creation rather than at construction.

Why this answer

Option A, widget['bg'] = 'blue', is correct because Tkinter widgets implement the mapping protocol for configuration, so assigning to a widget's option key via item assignment updates that option just like a configuration call. Option B, widget.config(bg='blue'), is correct because config() is the standard Tkinter method for changing one or more widget options after creation, and bg is a valid option name. Option C, widget.configure(bg='blue'), is correct because configure() is simply the full-name alias of config() and performs the identical option-setting operation.

Option D is not a valid Tkinter API, since there is no set_bg() method on widgets, and option E is incorrect because style is not a generic widget option that accepts a color string; styling is handled through ttk styles or specific options like bg.

48
Multi-Selectmedium

Which TWO of the following statements correctly describe the behavior of the Tkinter 'pack' geometry manager?

Select 2 answers
A.The manager automatically ignores the order in which pack() is called.
B.The 'side' parameter can be set to 'top', 'bottom', 'left', or 'right'.
C.Widgets are placed in a grid coordinate system.
D.Widgets are positioned at exact X and Y coordinates.
E.The 'fill' parameter can be set to 'x', 'y', 'both', or 'none'.
AnswersB, E

The side parameter accepts exactly these four cardinal values, anchoring the widget against that edge of the parent container and allocating the remaining cavity to subsequent widgets. This matches the stem's request for a correct description of pack's placement behaviour.

Why this answer

Option B is correct because pack()'s 'side' parameter accepts exactly the four values 'top', 'bottom', 'left', and 'right', which determine the edge of the container against which the widget is packed (defaulting to 'top'). Option E is correct because the 'fill' parameter accepts 'x', 'y', 'both', or 'none', controlling whether the widget stretches to fill available space along the horizontal axis, vertical axis, both, or neither. Option A is wrong because pack() honors call order: widgets are allocated space in the sequence pack() is invoked, so order directly affects layout.

Option C is wrong because the grid coordinate system belongs to the grid() geometry manager, not pack(). Option D is wrong because absolute X/Y positioning is the domain of the place() geometry manager, whereas pack() uses relative cavity-based allocation.

Exam trap

PCPP1 often tests whether candidates confuse the three Tkinter geometry managers — pack(), grid(), and place() — attributing grid coordinates or absolute positioning to pack().

49
Multi-Selecthard

Which THREE of the following are valid ways to pass arguments to a function called by a Tkinter button command?

Select 3 answers
A.command=lambda arg=arg1: my_func(arg)
B.command=lambda: my_func(arg1)
C.command=functools.partial(my_func, arg1)
D.command=my_func(arg1=value)
E.command=my_func(arg1)
AnswersA, B, C

The lambda captures arg1 as a default parameter at definition time, so each button's callback binds its own value rather than the loop variable's final state. This is the standard Tkinter pattern for passing arguments to command callbacks.

Why this answer

Option A is correct because a lambda with a default argument (arg=arg1) captures the value at definition time and passes it to my_func when the button is clicked, avoiding late-binding issues. Option B is correct because a zero-argument lambda that closes over arg1 defers execution of my_func(arg1) until the button is pressed, which is the standard Tkinter pattern for passing arguments. Option C is correct because functools.partial(my_func, arg1) creates a callable that already has arg1 bound, and Tkinter accepts any callable as the command.

Option D is wrong because my_func(arg1=value) is invoked immediately at widget creation, so command receives the function's return value rather than a callable. Option E is wrong for the same reason: my_func(arg1) executes right away and its result is assigned to command, not deferred until the button is clicked.

50
MCQeasy

Which widget is most suitable for displaying multi-line, editable text?

A.tk.Listbox()
B.tk.Entry()
C.tk.Text()
D.tk.Label()
AnswerC

tk.Text provides a multi-line editable buffer with insert, delete and index operations, unlike single-line Entry or read-only Label. It directly satisfies the requirement for displaying and editing multi-line content, supporting scrolling, tags and cursor navigation out of the box.

Why this answer

tk.Text is the Tkinter widget designed for multi-line, editable text input, supporting scrolling, indexing, tags, and embedded windows/images. It is the correct choice when users need to enter or edit paragraphs of text. Entry and Label are single-line or read-only, and Listbox is for selecting items from a list.

Exam trap

PCPP1 often tests whether candidates distinguish single-line Entry from multi-line Text, and whether they confuse read-only Label with editable input widgets.

How to eliminate wrong answers

Option A is wrong because tk.Listbox displays a scrollable list of items for selection; it does not support free-form multi-line text editing. Option B is wrong because tk.Entry is a single-line text input widget; it cannot display or edit multiple lines. Option D is wrong because tk.Label is a read-only display widget for static text or images; it is not editable at all.

51
MCQeasy

Which attribute of a Button widget controls the text displayed on it?

A.value
B.text
C.caption
D.label
AnswerB

The text attribute of a Button widget stores and displays the caption shown on the button face. Setting it changes the visible label, whereas attributes such as command or state govern behaviour rather than the displayed string.

Why this answer

The 'text' parameter defines the display label of the button.

52
MCQmedium

You need a color chooser dialog in your application. Which module contains this functionality?

A.tkinter.dialogs
B.tkinter.colorchooser
C.tkinter.colors
D.tkinter.widgets
AnswerB

`tkinter.colorchooser` provides the `askcolor()` function, which opens a native colour picker dialog and returns the chosen RGB values and hexadecimal string. It satisfies the stem's requirement for a colour chooser dialog directly, without extra dependencies, unlike `tkinter.ttk` widgets or third-party libraries.

Why this answer

The 'tkinter.colorchooser' module provides the askcolor() function.

53
Multi-Selecteasy

Which TWO of the following are valid ways to terminate a Tkinter script gracefully?

Select 2 answers
A.os.kill()
B.root.quit()
C.exit()
D.root.close()
E.root.destroy()
AnswersB, E

Calling `root.quit()` stops Tkinter's main loop, letting the script continue past `mainloop()` and exit cleanly. Unlike `root.destroy()`, which tears down the window and all widgets, `quit()` merely halts event processing, satisfying the requirement for graceful termination without destroying the application's widget hierarchy.

Why this answer

Option B, root.quit(), is correct because it tells the Tkinter mainloop to stop processing events and return control to the code after mainloop(), which is the standard graceful way to end the event loop while allowing cleanup code to run. Option E, root.destroy(), is also correct because it destroys the root window and all its child widgets, causing the mainloop to exit and the application to terminate cleanly. Option A, os.kill(), is not appropriate because it sends a low-level signal to a process (e.g., SIGTERM/SIGKILL) rather than performing a Tkinter-aware shutdown, so it bypasses widget cleanup.

Option C, exit(), is not a Tkinter method and is intended for interactive interpreters; calling it in a GUI script raises SystemExit abruptly rather than gracefully stopping the Tk mainloop. Option D, root.close(), is invalid because Tkinter's Tk root object has no close() method; the correct window-closing method is destroy().

54
MCQeasy

What is the primary function of the 'bg' parameter in a widget configuration?

A.Sets the button group.
B.Sets the border group.
C.Sets the background color.
D.Sets the base grid.
AnswerC

The `bg` parameter directly assigns a widget's background colour, satisfying the stem's requirement for its primary function. Tkinter applies this value to the widget's background pixel area, distinct from `fg`, which controls foreground text or content colour. No other parameter governs background rendering, confirming `bg` as the correct attribute.

Why this answer

In widget configuration (as used in Python GUI frameworks such as Tkinter and similar toolkits), the 'bg' parameter is the standard abbreviation for 'background', and it sets the background colour of the widget. It accepts colour names (e.g., 'red', 'blue') or hexadecimal colour codes (e.g., '#FF0000').

Exam trap

The trap here is that 'bg' is a short abbreviation, and candidates may guess at its meaning — the exam expects you to know that 'bg' universally stands for 'background' in widget configuration contexts, not 'button group', 'border group', or 'base grid'.

How to eliminate wrong answers

Option A is wrong because 'button group' would typically be configured via a different parameter (e.g., 'group' or a container widget), not 'bg'. Option B is wrong because 'border group' is not a standard widget configuration parameter, and border settings are usually controlled by 'bd' (border width) or 'relief'. Option D is wrong because 'base grid' is not a widget configuration parameter — grid geometry is managed by the 'grid()' method, not a 'bg' option.

55
MCQmedium

You want to bind a function 'on_click' to a left mouse button click on a Button widget. Which event sequence string is correct?

A.<Button-1>
B.<Mouse-1>
C.<Left-Click>
D.<Click-1>
AnswerA

Tkinter encodes mouse events as <MODIFIER-BUTTON-NUM>, where Button-1 denotes the left mouse button. Binding <Button-1> to the Button widget therefore fires on_click precisely on a left click, satisfying the stem's requirement without capturing middle or right button presses.

Why this answer

The event sequence '<Button-1>' corresponds to the primary (left) mouse button.

56
MCQmedium

How do you set a specific font for a widget?

A.widget.set_font('Arial', 12)
B.widget.style('Arial', 12)
C.widget.font = 'Arial 12'
D.widget.config(font=('Arial', 12))
AnswerD

Tkinter's config method accepts a font option, and a tuple of family and size sets that widget's typeface directly. Passing ('Arial', 12) assigns Arial at 12 points to the widget, satisfying the requirement to set a specific font.

Why this answer

The 'font' parameter accepts a tuple or string defining font family, size, and style.

57
MCQmedium

You are developing a Tkinter application that includes a Canvas widget for drawing a dynamic bar chart. The chart data updates every second, and you must redraw the bars. To avoid visual flicker and improve performance, you decide to reuse existing canvas items instead of deleting and recreating them. Which Canvas method should you use to change the height of an existing rectangle item identified by its item ID?

A.canvas.coords(item_id, x1, y1, x2, y2)
B.canvas.move(item_id, 0, delta_y)
C.canvas.scale(item_id, x_origin, y_origin, x_scale, y_scale)
D.canvas.itemconfig(item_id, height=new_height)
AnswerA

The coords() method changes the coordinates of an existing canvas item, such as a rectangle defined by two corners. It updates the item in place without deleting or recreating it, which is efficient and avoids flicker. For a rectangle, you provide the new x1, y1, x2, y2 values. This is the correct approach for dynamic updates.

Why this answer

To dynamically update the size of an existing canvas item, you should modify its coordinates. The coords() method allows you to set new coordinates for an item, effectively resizing or repositioning it without deleting and recreating. This is efficient and avoids flicker.

Other methods like itemconfig() are for changing options like fill, move() only translates, and scale() applies proportional scaling, which is not ideal for precise height adjustments.

Exam trap

The trap here is assuming that itemconfig() can change geometric properties like height for all canvas items, but rectangles are defined by coordinates, not a height attribute.

58
MCQhard

You have a Tkinter Entry widget and want to retrieve the text currently entered by the user. Which method do you call on the Entry instance?

A.entry.get()
B.entry.content()
C.entry.text()
D.entry.value()
AnswerA

Entry.get() reads the widget's current contents as a string, satisfying the requirement to retrieve user-entered text. It accepts optional index arguments, but with none it returns the entire field, which is the standard Tkinter approach.

Why this answer

The get() method is used to retrieve the current contents of Entry and Text widgets.

Ready to test yourself?

Try a timed practice session using only Graphical User Interface Programming questions.