在 OptionMenu 选择更改后更新标签文本 [英] Updating Label text after OptionMenu selection changes
本文介绍了在 OptionMenu 选择更改后更新标签文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的目标是在每次选择选项菜单 w
中的新项目时更新标签 price
的内容.到目前为止,这是我的代码,但它返回了我不知道如何修复的错误.
My objective is to update the contents of the label price
, every time that a new item in option menu w
is selected. This is my code so far, but it is returning errors that I am not sure how to fix.
class App(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
Label(master, text="Ore:").grid(row=0)
Label(master, text="Price:").grid(row=1)
self.price = Label(master, text="0.00").grid(row=1, column=1)
variable = StringVar(master)
variable.set("Select an ore") # default value
def displayPrice(self):
self.price = orePrice[self.w.get()]
self.w = OptionMenu(master, variable, *orePrice, command=displayPrice).grid(row=0, column=1)
# here is the application variable
self.contents = StringVar()
# set it to some value
self.contents.set("this is a variable")
# tell the entry widget to watch this variable
#self.w.bind('<Button-1>', )
您可以假设:
orePrice = {'Gold': 300, 'Silver': 50, 'Bronze': 10} # etc... you can add more if you feel like it.
我是 Python GUI 的新手,因此代码凌乱和/或写得不好.
I'm a newbie at Python GUI, hence the messy and/or badly written code.
推荐答案
我修改了你的代码.现在,每当您更改矿石类型时,价格字段都会更新:
I ammended your code. Now whenever you change ore type, the price field is updated:
from tkinter import *
class App(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
Label(master, text="Ore:").grid(row=0)
Label(master, text="Price:").grid(row=1)
self.priceVar = StringVar()
self.priceVar.set("0.00")
self.price = Label(master, textvariable=self.priceVar).grid(row=1, column=1)
self.orePrice = {'Gold': 300, 'Silver': 50, 'Bronze': 10}
variable = StringVar(master)
variable.set("Select an ore") # default value
self.w = OptionMenu(master, variable, *self.orePrice, command=self.displayPrice).grid(row=0, column=1)
# here is the application variable
self.contents = StringVar()
# set it to some value
self.contents.set("this is a variable")
# tell the entry widget to watch this variable
#self.w.bind('<Button-1>', )
def displayPrice(self, value):
self.priceVar.set(self.orePrice[value])
root = Tk()
app = App(root)
root.mainloop()
这篇关于在 OptionMenu 选择更改后更新标签文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文