0

Basically, the problem is that this doesn't work:

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()

Whereas this does:

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()

Why is it that I can't place an entry into a method without getting errors? The specific error here is that 'song' isn't being found in the run method, giving the following error:

NameError: global name 'song' is not defined

How do I change it so that this error doesn't happen, but the entry is still in a method?

4

1 回答 1

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()
于 2013-07-14T16:34:19.233 回答