Home > Software design >  Using dictionary to make Option menu and receive the values on selection, with tkinter
Using dictionary to make Option menu and receive the values on selection, with tkinter

Time:08-09

I am try to use a OptionMenu in my GUI, I am unable to get the value of selected item in OptionMenu.I am unable to write the function properly.

Following is my code.

from tkinter import *
root = Tk()

variable = StringVar(root)
options = {"one": 1, "two": 2, "three": 3}

O_menu = OptionMenu(root, variable, *options.keys()).pack()

def sample():
    #here i want to write a function so that when I select "one", the result should print 1.
    pass


bu = Button(root, text="print", command=sample).pack()

root.mainloop()

Additionally I want OptionMenu with default value of one to be selected when I start the GUI.

CodePudding user response:

If you use variable in OptionMenu then you can use

  • variable.get() to get value selected in OptionMenu
  • variable.set("one") to set value in OptionMenu

Minimal working code with other changes

import tkinter as tk  # PEP8: `import *` is not preferred

# --- functions ---  # PEP8: all functions before main code

def sample():
    selected = variable.get()
    print(selected, options[selected])

# --- main ---

options = {"one": 1, "two": 2, "three": 3}

root = tk.Tk()

variable = tk.StringVar(root)
variable.set("one")

o_menu = tk.OptionMenu(root, variable, *options.keys())
o_menu.pack()

bu = tk.Button(root, text="print", command=sample)
bu.pack()

root.mainloop()

PEP 8 -- Style Guide for Python Code

CodePudding user response:

Here is the solution:

from tkinter import *
root = Tk()

variable = StringVar(root)
options = {"one": 1, "two": 2, "three": 3}
variable.set("one")

O_menu = OptionMenu(root, variable, *options.keys()).pack()


def sample():
    result = variable.get()
    print(options[result])

bu = Button(root, text="print", command=sample).pack()

root.mainloop()
  • Related