在OptionMenu选择更改后更新标签文本

时间:2014-06-24 16:23:19

标签: python-3.x tkinter

我的目标是每次选择选项菜单price中的新项目时更新标签w的内容。这是我的代码到目前为止,但它返回错误,我不知道如何修复。

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的新手,因此编写了混乱和/或编写错误的代码。

1 个答案:

答案 0 :(得分:1)

我推荐了你的代码。现在每当您更改矿石类型时,价格字段都会更新:

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()  
相关问题