【问题标题】:How to place tkinter entries into a method?如何将 tkinter 条目放入方法中?
【发布时间】:2013-07-14 16:29:05
【问题描述】:

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

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:未定义全局名称“歌曲”

如何更改它以使此错误不会发生,但条目仍在方法中?

【问题讨论】:

    标签: python input tkinter


    【解决方案1】:

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

    另一种方式(把run放在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()
    

    【讨论】:

      猜你喜欢
      • 2021-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-19
      • 1970-01-01
      • 2014-08-09
      • 2018-09-15
      相关资源
      最近更新 更多