我正在使用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()
答案 0 :(得分:2)
使用lambda
功能:
add_button = Button(wrapper, text="add", command=lambda:addmeter(self))
修改强>
你是说这个吗?
我在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()
,以使名称更符合逻辑。