基本上,问题是这不起作用:
def run():
print song.get()
def startGUI():
root = Tk()
songLabel = Label(root, text="Enter the song:")
song = Entry(root)
submit = Button(root, text="Download", command = run)
songLabel.pack()
song.pack()
submit.pack()
root.mainloop()
if __name__ == "__main__":
startGUI()
这样做:
def run():
print song.get()
root = Tk()
songLabel = Label(root, text="Enter the song:")
song = Entry(root)
submit = Button(root, text="Download", command = run)
songLabel.pack()
song.pack()
submit.pack()
root.mainloop()
为什么我不能在没有错误的情况下将一个条目放入方法中? 这里的具体错误是在run方法中找不到'song',给出以下错误:
NameError:未定义全局名称“歌曲”
如何更改它以便不会发生此错误,但该条目仍在方法中?
答案 0 :(得分:2)
song
是局部变量,只能在startGUI
函数内访问,run
无法访问。
song
是全局变量,可以访问模块中的任何位置。
以下代码显示了使第一个代码生效的一种方法。 (明确地传歌)。
from Tkinter import *
def run(song):
print song.get()
def startGUI():
root = Tk()
songLabel = Label(root, text="Enter the song:")
song = Entry(root)
submit = Button(root, text="Download", command=lambda: run(song))
songLabel.pack()
song.pack()
submit.pack()
root.mainloop()
if __name__ == "__main__":
startGUI()
另一种方式(在startGUI中运行):
from Tkinter import *
def startGUI():
def run():
print song.get()
root = Tk()
songLabel = Label(root, text="Enter the song:")
song = Entry(root)
submit = Button(root, text="Download", command=run)
songLabel.pack()
song.pack()
submit.pack()
root.mainloop()
if __name__ == "__main__":
startGUI()
您也可以使用课程。
from Tkinter import *
class SongDownloader:
def __init__(self, parent):
songLabel = Label(root, text="Enter the song:")
self.song = Entry(root)
submit = Button(root, text="Download", command=self.run)
songLabel.pack()
self.song.pack()
submit.pack()
def run(self):
print self.song.get()
if __name__ == "__main__":
root = Tk()
SongDownloader(root)
root.mainloop()