【发布时间】:2015-08-13 17:04:02
【问题描述】:
我对标题所说的内容有疑问。我有这段代码:
class eventAdd:
def __init__(self):
class agendaEvent:
def __init__(self, master):
self.frame = Frame(master, padx=10, pady=10)
稍后,在 eventAdd 类之外,但与 eventAdd 处于同一级别,我有:
def addEvent():
instance = eventAdd()
doneButton = Button([PROBLEM AREA], text="Done", command=done)
我输入 [PROBLEM AREA] 的地方很明显是问题区域。我想在 eventAdd 内的议程事件内的框架内创建 doneButton。是否可以在类内部的 init 内部的类内部的 init 内部引用一个变量,以便像这样使用?如果有,怎么做?
对于我可能犯下的任何编程错误,我深表歉意。我对编程还很陌生,我还不确定最好的方法是什么。欢迎提出任何建议。
提前致谢。
编辑:完整脚本:
from Tkinter import *
from functools import partial
class eventAdd:
def __init__(self):
class agendaEvent:
def __init__(self, master):
self.frame = Frame(master, padx=10, pady=10)
self.frame.grid()
self.name = Entry(self.frame)
self.name.grid(row=1, column=0)
self.time = Entry(self.frame, width=10)
self.time.grid(row=1, column=1, padx=5)
self.label1 = Label(self.frame, text="Event Name")
self.label1.grid(row=0, column=0)
self.label2 = Label(self.frame, text="Minutes")
self.label2.grid(row=0, column=1)
def addOne(master):
this_instance = agendaEvent(master)
rem = Button(this_instance.frame, text="Remove", bg="lightblue",
command=partial(remove_class, this_instance))
rem.grid(row=1, column=3)
def remove_class(instance):
instance.frame.destroy()
instance = ""
def done():
print('tbd')
window = Tk()
addOneButton = Button(window, text="+1", command=partial(addOne, window))
addOneButton.grid(row=1, column=0)
window.mainloop()
def addEvent():
instance = eventAdd()
doneButton = Button([PROBLEM AREA], text="Done", command=done)
doneButton.pack()
def done():
print('tbd')
root = Tk()
addEventButton = Button(root, text="Add Events", command=addEvent)
addEventButton.pack()
root.mainloop()
编辑:错误
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1532, in __call__
return self.func(*args)
File "C:/Users/John Grady/PycharmProjects/Dad's Agenda/scripts/main.py", line 41, in addEvent
instance = agendaEvent(window)
File "C:/Users/John Grady/PycharmProjects/Dad's Agenda/scripts/main.py", line 6, in __init__
self.frame = Frame(master, padx=10, pady=10)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 2565, in __init__
Widget.__init__(self, master, 'frame', cnf, {}, extra)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 2086, in __init__
(widgetName, self._w) + extra + self._options(cnf))
TclError: can't invoke "frame" command: application has been destroyed
【问题讨论】:
-
为什么要在
__init__中声明一个类?你希望它做什么? -
使用global variable 可能会对您有所帮助。
-
@JunYoungGwak 请不要。
-
@user2357112 在 eventAdd 的 init 内,还定义了其他影响类议程事件的函数。
-
@JohnHall:为什么那些在
__init__里面?您确定在__init__之外定义这些东西会更好吗,可能完全在eventAdd之外,而只是将适当的参数传递给agendaEvent?