在tkinter中设置OptionMenu的标签值

时间:2018-03-14 11:52:09

标签: python-3.x tkinter label optionmenu

我想将标签值设置为当前optionmenu值的值。如果后者改变,我希望前者也改变。我的问题是这个gui元素是在不同的类中定义的(我希望它们是这样的),但我不知道如何将它们连接在一起。没有课程,我知道我可以使用OptionMenu的{​​{1}}方法来设置command的值。但是将它们放入Frame容器中我会被卡住。 这是一个简单而有效的代码,我想要解决的问题:

Label

你能给我一些帮助吗?非常感谢。

1 个答案:

答案 0 :(得分:0)

根据@ j_4321的建议,我在这里发布解决了我的问题的解决方案。我在代码行之间的注释中提供了解释。

from tkinter import *
root = Tk()
opt=['Jan', 'Feb', 'March']

var = StringVar(root)  # initialization of a common StringVar for both OptionMenu and Label widgets

class MyOptMenu(Frame):
    def __init__(self, parent=None):
        Frame.__init__(self, parent)
        self.pack()
        var.set(opt[0])  # give an initial value to the StringVar that will be displayed first on the OptionMenu
        self.om = OptionMenu(self, var, *opt)
        self.om.pack(side=TOP)
        var.trace('w', self.getValue)   # continuously trace the value of the selected items in the OptionMenu and update the var variable, using the function self.getValue
    def getValue(self, *args):
        return(var.get())  # return the current value of OptionMenu

class MyLabel(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.pack()
        self.lab = Label(self, textvariable = var, bg='white')  # use the same StringVar variable (var) as the OptionMenu. This allows changing the Label text instantaneously to the selected value of OptionMenu
        self.lab.pack(side=TOP)

a = MyOptMenu(root)
b = MyLabel(root)
root.mainloop()