【发布时间】:2017-11-23 23:07:18
【问题描述】:
这里我们使用 GUI 来选择手机并自动更新手机成本。 问题是如何更新小部件字典中的 tkinter 文本变量。
我想扩展这个更简单的解决方案:Updating Label text after OptionMenu selection changes
您将通过运行下面的代码看到,当您选择手机时,只有最后一行(错误地)更新。我已经尝试了我能想到的一切,但我太缺乏经验,无法了解如何让函数“displayPrice”为每一行引用一个值。请您帮忙,谢谢。
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()
【问题讨论】:
-
这是您提供的一段很长的代码。有什么方法可以将其减少到影响结果的关键部分?
-
@asongtoruin - 谢谢,我同意。我已经缩短了它并删除了所有按钮和功能。我再看看。
-
这段代码需要减少。例如,您真的需要 13 个标签小部件吗?为什么你不能只用一两个来回答这个问题?特定的字体或页面标题真的很重要吗?只需减少标签数量即可删除 40 多行。
-
@BryanOakley - 谢谢。又学到了一个菜鸟的教训。希望现在,这是可以接受的代码来寻求人们的帮助。
-
@asongtoruin - 抱歉,我之前用臃肿的代码浪费了你的时间。我可以礼貌地重新点燃你对这个问题的兴趣吗?
标签: python user-interface dictionary tkinter