如何将tkinter条目放入方法中?

2024-04-27 00:20:12 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上,问题是这不起作用:

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”,导致以下错误:

名称错误:未定义全局名称“song”

如何更改它以避免发生此错误,但条目仍在方法中?你知道吗


Tags: 方法runtextgetsongdef错误root
1条回答
网友
1楼 · 发布于 2024-04-27 00:20:12

第一个代码中的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()

你也可以用class。你知道吗

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

相关问题 更多 >