从类中调用全局函数。 Python 2.7使用Tkinter

时间:2013-11-14 00:05:38

标签: class python-2.7 tkinter

我正在使用Tkinter创建一个LabelFrame类,它通过按下一个添加按钮来创建一个包含我希望逐个包含的项目组的包装器,该按钮调用一个函数来创建更多该项。

我运行了代码,在那里我可以看到LabelFrame和addbuttun。但是,当我按下按钮时,调用的函数出现错误:

addmeter() takes exactly 1 argument (0 given)

我需要这个函数在LabelFrame中添加一个类,这就是我被困住的地方。

我在下面列出了我的代码。

from Tkinter import *

    root = Tk()
    root.title("LabelFrame with embedded add voltmeters")
    root.geometry("600x200+400+400")


    def addmeter(self):
            #Create frame for the voltmeter
        voltsmet1 = LabelFrame(self.master, text = "Volts")
            #add Text box for the serial output. 
        voltinfo = Text(voltsmet1, bg="BLACK",  height=10, width =20 )
            #add in reg command to find our data from queue and display it



            #packs the widgets on the grid for display
        voltsmet1.pack(side=LEFT, expand=True)
        voltinfo.pack(side=LEFT,  expand=True)      

    class wrapper(LabelFrame):
        def __init__(self,master):
            self.master = master
            self.create_wrapper()

        def create_wrapper(self):
            wrapper = LabelFrame(self.master, text = "Volt Meters")
            add_button = Button(wrapper, text="add", command=addmeter)
            wrapper.pack()
            add_button.pack()

    new= wrapper(root)
    root.mainloop()

1 个答案:

答案 0 :(得分:2)

使用lambda功能:

add_button = Button(wrapper, text="add", command=lambda:addmeter(self))

修改

你是说这个吗?

enter image description here

我在lambda函数中使用wrapper

add_button = Button(wrapper, text="add", command=lambda:addmeter(wrapper))

我删除了.master

中的addmeter

完整代码:

from Tkinter import *

root = Tk()
root.title("LabelFrame with embedded add voltmeters")
root.geometry("600x200+400+400")


def addmeter(parent):
        #Create frame for the voltmeter
    voltsmet1 = LabelFrame(parent, text = "Volts")
        #add Text box for the serial output. 
    voltinfo = Text(voltsmet1, bg="BLACK",  height=10, width =20 )
        #add in reg command to find our data from queue and display it



        #packs the widgets on the grid for display
    voltsmet1.pack(side=LEFT, expand=True)
    voltinfo.pack(side=LEFT,  expand=True)      

class wrapper(LabelFrame):
    def __init__(self,master):
        self.master = master
        self.create_wrapper()

    def create_wrapper(self):
        wrapper = LabelFrame(self.master, text = "Volt Meters")
        add_button = Button(wrapper, text="add", command=lambda:addmeter(wrapper))
        wrapper.pack()
        add_button.pack()

new= wrapper(root)
root.mainloop()

btw:我在self中将名称parent更改为addmeter(),以使名称更符合逻辑。