简体   繁体   中英

Tkinter update label on optionmenu dictionary of dictionaries

Here we use a GUI to select a handset and auto update a handset_cost. The problem is how to update a tkinter textvariable in a dictionary of widgets.

I'd like to extend this simpler solution: Updating Label text after OptionMenu selection changes

You'll see from running the code below, only the final row is (incorrectly) updated when you select a handset. I've tried everything I can think of but I'm too inexperienced to see how to get the function 'displayPrice' to reference a value for each row. Please can you help, thanks.

import tkinter as tk
import datetime


class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent, background="black")
        root.title("Mobile Order Quote")

        table = tk.Frame(self, background="black")
        table.pack(side="top", fill="both", expand=True)

        data = [(1, ),(2, ),(3, ),(5, )]

        handset_dict1 = {'apple_iphone': 500.0, 'two_cans_plus_string': 50.0, 'samsung_galaxy': 800.0, 'none': 0.0}                     

        table = tk.Frame(self, background="black")
        table.pack(side="top", fill="both", expand=True)
        self.widgets = {}

            # MAKE 'big_tuple': solving the list of tuples problem - make a tuple of tuples and format too
        x = list(data)
        list_of_lists = [list(elem) for elem in x]

        big_list = []
        for i in list_of_lists:
            data1=(str(i[0]))
            big_list.append(data1)

        big_tuple = tuple(big_list)
        #global big_tuple

        row = 0
        for rent_id in (big_tuple):

            HLabel0 = tk.Label(table, text = "ID", fg = "white", background="black")
            HLabel9 = tk.Label(table, text = "Proposed_Handset", fg = "white", background="black")
            HLabel10 = tk.Label(table, text = "Handset_Cost", fg = "white", background="black")

            HLabel0.grid(row = 0, column = 0, padx=1, pady=1) 
            HLabel9.grid(row = 0, column = 9, padx=1, pady=1)
            HLabel10.grid(row = 0, column = 10, padx=1, pady=1)

            row += 1
            handset = tk.StringVar(root) # creates tkvar for the handsets
            handset.set('none')

            handsetCost = tk.DoubleVar(root)
            handsetCost.set(0)

            def displayPrice(value):
                handsetCost.set(handset_dict1[value])


            self.widgets[rent_id] = {
                "rent_id": tk.Label(table, text=rent_id),
                "handset": tk.OptionMenu(table, handset, *handset_dict1.keys(), command=displayPrice, ), 
                "handset_cost": tk.Label(table, textvariable =handsetCost), }

            self.widgets[rent_id]["rent_id"].grid(row=row, column=0, sticky="nsew", padx=1, pady=1)
            self.widgets[rent_id]["handset"].grid(row=row, column=9, sticky="nsew", padx=1, pady=1)
            self.widgets[rent_id]["handset_cost"].grid(row=row, column=10, sticky="nsew", padx=1, pady=1)


if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)

    root.mainloop()

The working solution changed considerably from the original code.

I've posted a solution in case it helps someone.

The handset and handset_cost variables were initially separated because we didn't want the string and float components together in one variable. However, the solution was to simply combine them as a single field:

HLabel9= tk.Label(table, text = "Proposed_Handset_&_cost")


"handset": ttk.Combobox(table, textvariable=handset, 
               values[*handset_dict1], ),

We then extracted the values, for example:

hs_buy_list = []


for rent_id in (sorted(self.widgets.keys())):
        hs_buy_price =  self.widgets[rent_id]['handset'] # handset and buy
        new_hs_buy = hs_buy_price.get()
        hs_buy_list.append(new_hs_buy)

buy_hs_int = [] # splits out the buy price of handsets 
        for i in hs_buy_list:
            buy_hs_int.append(i.split(':')[1].rstrip('}'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM