Python Forum
Inserting Numerical Value to the Element in Optionlist and Printing it into Entry
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Inserting Numerical Value to the Element in Optionlist and Printing it into Entry
#2
This code creates a dictionary capable menu option class.
import tkinter as tk

class MyOptionMenu(tk.OptionMenu):
    """An option menu that takes a dictionary instead of a list.
    I display the dictionary keys, but I return the dictionary values.
    """
    def __init__(self, parent, options, width=None, command=None):
        self.values = options
        self.keys = {value: key for key, value in options.items()}
        self.var = tk.StringVar(parent, list(options.keys())[0])
        self.var.trace('w', self._value_changed)
        super().__init__(parent, self.var, *options.keys())
        self.command = command
        if width is not None:
            self['width'] = width

    def _value_changed(self, *_):
        """Called when self.var is written.  Call callback function."""
        if self.command:
            self.command(self.value)

    @property
    def value(self):
        """Return the value of the selected option"""
        return self.values[self.var.get()]

    @value.setter
    def value(self, new_value):
        """Set the selected option by value"""
        self.var.set(self.keys[new_value])

    @property
    def key(self):
        """Return the selected option"""
        return self.var.get()

    @key.setter
    def key(self, new_key):
        """Set the selected option"""
        self.var.set(new_key)


class Window(tk.Tk):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        frame = tk.Frame(self)
        label = tk.Label(frame, text="Pick a Building Type")
        self.option_menu = MyOptionMenu(
            frame,
            {"Museum": 100, "School": 200, "Library": 300, "House": 400, "Bath": 500},
            width=20,
            command=self.select_option)
        self.display = tk.Label(self, width=20)
        frame.pack(padx=20, pady=20)
        label.pack(side=tk.LEFT)
        self.option_menu.pack(side=tk.LEFT, padx=(5, 0))
        self.display.pack(side=tk.TOP, padx=20, pady=(0, 20))
        self.option_menu.value = 100

    def select_option(self, value):
        self.display['text'] = f'{self.option_menu.key} = {value}'


Window().mainloop()
You could write a class like this that makes OptionMenu work the way you like, or your can have the option menu call a function in your program that converts the selection to the matching value. The important part is tying a function to the user making a selection. In the example above this is done by adding a trace to the option menu variable. Another way to do this is specify a "command" callback when creating the option menu.
Reply


Messages In This Thread
RE: Inserting Numerical Value to the Element in Optionlist and Printing it into Entry - by deanhystad - Jan-30-2023, 05:16 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  restrict user input to numerical values MCL169 2 1,843 Apr-08-2023, 05:40 PM
Last Post: MCL169
  Changing a string value to a numerical value using python code and a lamda function Led_Zeppelin 6 2,815 Jul-05-2022, 11:29 PM
Last Post: deanhystad
  Sorting numerical values provided by QAbstractTableModel BigMan 0 2,084 Jun-04-2022, 12:32 AM
Last Post: BigMan
  How to plot 3D graph of non numerical value? Gevni 0 2,709 Mar-05-2021, 02:50 PM
Last Post: Gevni
  change numerical values to categorical names JoeOpdenaker 3 3,908 Nov-02-2020, 01:32 PM
Last Post: DeaD_EyE
  Problem printing last element from a list tester_V 3 3,927 Oct-30-2020, 04:54 AM
Last Post: tester_V
  Filtering Excel Document Data Based On Numerical Values eddywinch82 30 14,775 Feb-25-2020, 06:08 PM
Last Post: eddywinch82
  Unable to locate element no such element gahhon 6 5,693 Feb-18-2019, 02:09 PM
Last Post: gahhon
  Change single element in 2D list changes every 1D element AceScottie 9 14,182 Nov-13-2017, 07:05 PM
Last Post: Larz60+
  How do I loop through a list and delete numerical elements that are 1 lower/higher? neko 4 5,361 Sep-05-2017, 02:25 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020