How to detect when an OptionMenu or Checkbutton changes in Tkinter?

PythonTkinterGUI-Programming

Let us suppose that in a particular application, we have some fixed set of options or choices for the user in a drop-down list. The Options or Choices can be created using the OptionMenu Widget Constructor.

OptionMenu(window, variable, choice1, choice2, choice3……)

Once the option is created, it can be detected by a click event which generally prints whether a particular option is selected or not. For this example, we will simply create an application where a check button will be present with some choices from the range (1 to 9). By default, the button is set to “1” using the set method. Selecting other options will print the button on the screen.

Example

#Import the tkinter library
from tkinter import *

#Create an instance of tkinter frame
tk = Tk()
tk.geometry("700x300")

#Create the option and Check Button Event
def OptionMenu_CheckButton(event):
   print(var.get())
   pass

#Create the variables
var = StringVar();var.set("1")
options = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
OptionMenu(tk, var, *(options), command =
OptionMenu_CheckButton).pack()
tk.mainloop()

Output

Running the above code will trace the options selected by the user and print it on the screen.

raja
Published on 04-Mar-2021 14:06:31
Advertisements