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
#1
Question 
Hello. I'm just learning Python. I have confronted a problem in my study.

I have an optionlist for building types (Residential, Museum, Hospital, Hotel etc.) but I need to convert these building types into numbers (fire load 'MJ/kg').

In other words, I want each building type to have its own "Numerical data of fire load".

For example, I would like "Museum" to appear in the option list, but when I select the museum, "100" should be written in the relevant entry.

How can it be done? Thank you in advance. Smile


options_list = {"Museum": 100,
"School": 200,
"Library": 300,
"House": 400,
"Bath": 500}

value_inside = tkinter.StringVar(Variable)
value_inside.set("Pick a Building Type")

question_menu = tkinter.OptionMenu(window, value_inside, *options_list)
question_menu.place(x=395, y=253)

building_types = tkinter.Entry(window, textvariable=value_inside, state=NORMAL, bd=5, fg='black',
font=("Helvetica", 12, BOLD))
building_types.place(x=292, y=255, width=100, height=30)
Larz60+ write Jan-29-2023, 11:21 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Fixed for you this time. Please use bbcode tags on future posts. Thank you
Reply
#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


Possibly Related Threads…
Thread Author Replies Views Last Post
  restrict user input to numerical values MCL169 2 931 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 1,631 Jul-05-2022, 11:29 PM
Last Post: deanhystad
  Sorting numerical values provided by QAbstractTableModel BigMan 0 1,375 Jun-04-2022, 12:32 AM
Last Post: BigMan
  How to plot 3D graph of non numerical value? Gevni 0 2,231 Mar-05-2021, 02:50 PM
Last Post: Gevni
  change numerical values to categorical names JoeOpdenaker 3 2,956 Nov-02-2020, 01:32 PM
Last Post: DeaD_EyE
  Problem printing last element from a list tester_V 3 2,417 Oct-30-2020, 04:54 AM
Last Post: tester_V
  Filtering Excel Document Data Based On Numerical Values eddywinch82 30 10,799 Feb-25-2020, 06:08 PM
Last Post: eddywinch82
  Unable to locate element no such element gahhon 6 4,519 Feb-18-2019, 02:09 PM
Last Post: gahhon
  Change single element in 2D list changes every 1D element AceScottie 9 12,098 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 4,325 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