我有一些代码的一部分是这样的:
def topLevel():
bugsendwindows = Toplevel(background="grey")
bugsendwindows.title("report bug")
buglabel1 = Label(bugsendwindows, text='title', background="white")
buglabel1.place(x=10, y=20)
bugtitleentry = Entry(bugsendwindows)
bugtitleentry.place(x=50, y=20)
bugtitleentry.focus_set()
buglabel2 = Label(bugsendwindows, text="email", background="white")
buglabel2.place(x=10, y=60)
bugemailentry = Entry(bugsendwindows)
bugemailentry.place(x=60, y=60)
bugemailentry.focus_set()
buglabel3 = Label(bugsendwindows, text="data", background="white")
buglabel3.place(x=10, y=100)
bugdataentry = Entry(bugsendwindows)
bugdataentry.place(x=60, y=100, height=60)
bugdataentry.focus_set()
def Enter():
global bugtitleentry
global bugemail
global bugdata
bugtitle = bugtitleentry
bugemail = bugemailentry
bugdata = bugdataentry
localtime = time.asctime(time.localtime(time.time()))
bugwrite = open("bugreport", "w")
bugwrite.write("title:")
bugwrite.write(bugtitle, "\n")
bugwrite.write("writer email:")
bugwrite.write(bugemail, "\n")
bugwrite.write("data:")
bugwrite.write(bugdata, "\n")
bugwrite.close()
bugsend = Button(bugsendwindows, text="send",
command=Enter)
bugsend.place(x=10, y=150)
但是,每次点击发送时,都会说出这样的话:
bugtitle = bugtitleentry
NameError: global name 'bugtitleentry' is not defined
如何修复它以便Enter可以从topLevel将数据写入文件?
答案 0 :(得分:1)
由于Enter
嵌套在topLevel
内,它将从闭包中获取这些名称,并且不需要global
语句。
# ... <snip>
def Enter():
bugtitle = bugtitleentry
bugemail = bugemailentry
# </snip> ...
但是,作为旁注,我不确定数据写入是否会按预期工作。您可能需要在.get()
对象上使用Entry
方法。 e.g:
bugwrite.write(bugtitle.get() + "\n") # and file.write only takes 1 argument!