0

我正在使用 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()
4

1 回答 1

2

Use lambda function:

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

EDIT:

Do you mean this ?

enter image description here

I use wrapper in lambda function

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

and I remove .master in addmeter

Full code:

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: I change name self to parent in addmeter() to make names more logical.

于 2013-11-14T02:30:51.957 回答