【问题标题】:Updating Label text after OptionMenu selection changes在 OptionMenu 选择更改后更新标签文本
【发布时间】:2014-06-24 16:23:19
【问题描述】:

我的目标是更新标签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 的新手,因此代码混乱和/或写得不好。

【问题讨论】:

    标签: python-3.x tkinter


    【解决方案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()  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-25
      • 2022-01-18
      • 2016-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多