使用Tkinter时的可变跟踪方法错误

时间:2017-06-21 06:12:32

标签: python python-2.7 tkinter tk tkinter-canvas

我有两个字符串变量,我想跟踪相同的回调,这些变量是两个下拉菜单。

当我将两个变量都跟踪到同一个函数时,就会出现问题。我得到了AttributeError,这是一个错误的例子

import Tkinter as tk
import ttk

class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.handlersList = ["handlr1", "handlr2", "handlr3"]
        self.modemList = ["modem1","modem2","modem3"]

        self.selctdModm = tk.StringVar(self)
        self.selctdModm.set("Select a Modem")
        self.defaultModem = "Select a Modem"
        self.modemList.insert(0,self.defaultModem)

        self.selctdModm.trace('w', self.start) 
        self.drop_Menu_Modems = ttk.OptionMenu(self, self.selctdModm,
                                         self.modemList[0],
                                         *self.modemList,
                                         command= "")
        self.drop_Menu_Modems.pack()
        self.drop_Menu_Modems.config( width = 15)




        self.selctdHandler = tk.StringVar(self)
        self.selctdHandler.set("Select a Handler")
        self.defaultHandlr = "Select a Handler"
        self.handlersList.insert(0,self.defaultHandlr)  

        self.selctdHandler.trace('w', self.start)                
        self.drop_Menu_handlrs = ttk.OptionMenu(self, self.selctdHandler,
                                                self.handlersList[0],
                                                *self.handlersList,
                                                command= "")
        self.drop_Menu_handlrs.pack()
        self.drop_Menu_handlrs.config(width = 15 )


    def start(self, *args):

        handler = self.selctdHandler.get()



app = SampleApp()
app.mainloop()

1 个答案:

答案 0 :(得分:1)

当您将跟踪添加到selctdModm时,未创建self.selctdHandler,因此您获得AttributeError

在初始化self.selctdModm.trace('w', self.start)之后移动self.selctdHandler