Place the following code just above the previous code, which is located at the bottom of the module, and which starts the main window's event loop, like we did in the previous recipes:
- Start with the GUI_textbox_widget.py module and save it as GUI_set_focus.py.
- Use the name_entered variable we assigned the ttk Entry widget instance to and call the focus() method on this variable:
name_entered.focus()
The preceding instructions produce the following code (GUI_set_focus.py):
- Run the code and observe the output.
If you get some errors, make sure you are placing calls to variables below the code where they are declared. We are not using OOP as of now, so this is still necessary. Later, it will no longer be necessary to do this.
On a Mac, you might have to set the focus to the GUI window first before being able to set the focus to the Entry widget in this window.
Adding line 38 of the Python code places the cursor in our text Entry widget, giving the text Entry widget the focus. As soon as the GUI appears, we can type into this textbox without having to click it first. The resulting GUI now looks like this, with the cursor inside the Entry widget:
Note how the cursor now defaults to residing inside the text entry box.
We can also disable widgets. Here, we are disabling the button to show the principle. In larger GUI applications, the ability to disable widgets gives you control when you want to make things read only. Most likely, those would be combobox widgets and Entry widgets, but as we have not yet gotten to those widgets yet, we will use our button.
To disable widgets, we will set an attribute on the widget. We can make the button disabled by adding the following code below line 37 of the Python code to create the button:
- Use the GUI_set_focus.py module and save it as GUI_disable_button_widget.py.
- Use the action button variable to call the configure method and set the state attribute to disabled:
action.configure(state='disabled')
- Call the focus() method on the name_entered variable:
name_entered.focus()
The preceding instructions produce the following code (GUI_disable_button_widget.py):
- Run the code. After adding the preceding line of Python code, clicking the button no longer creates an action:
Let's go behind the scenes to understand the code better.