【问题标题】:Returning a value after calling a function with a button in Tkinter在 Tkinter 中使用按钮调用函数后返回一个值
【发布时间】:2011-03-21 06:06:32
【问题描述】:
from Tkinter import *
from tkFileDialog import askopenfilename
from PIL import Image
def main():
    filename = askopenfilename(filetypes=[("Jpeg","*.jpg")])
return filename
root = Tk()
button = Button(root,text="Open",command=main)
button.pack()
root.title("Image Manipulation Program")
root.mainloop()

一般来说,我是一个编程新手,但我正在尝试通过 Tkinter GUI 库制作一个成像程序。我需要在上面的代码中做的是返回存储在文件名中的字符串,这样它就在程序的全局范围内,我可以使用它。问题是我不知道在使用按钮调用函数时该怎么做。我在任何网站上都找不到这个问题的答案,所以我希望有人能帮助我解决这个问题。

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    如果您将class based approach 用于 Tk 应用程序,则可以将它们分配给实例变量,而不是从事件处理程序返回值。这是最好的方法,因为基于函数的 GUI 应用程序不能很好地扩展,因为需要将东西放在模块范围内。

    from Tkinter import *
    
    class Application(Frame):
    
        def main(self):
            self.filename = askopenfilename(filetypes=[("Jpeg","*.jpg")])
    
        def createWidgets(self):
            self.button = Button(root,text="Open",command=self.main)
            self.button.pack()
    
        def __init__(self, master=None):
            Frame.__init__(self, master)
            self.filename = None
            self.pack()
            self.createWidgets()
    
    root = Tk()
    root.title("Image Manipulation Program")
    app = Application(master=root)
    app.mainloop()
    

    【讨论】:

      【解决方案2】:

      通常,使用全局变量在程序中传递信息是不好的做法。但是,如果您确实必须这样做,请使用可变数据类型(例如列表或字典)作为全局变量,并通过回调函数 main 更改其内容。

      returned_values = {}    # Create an empty dict.
      def main():
          returned_values['filename'] = askopenfilename(filetypes=[("Jpeg","*.jpg")])
          # returned_values['filename'] may now be accessed in the global scope.
      

      如果您打算经常这样做,请考虑实现您自己的类来传递信息。

      【讨论】:

        猜你喜欢
        • 2021-05-31
        • 1970-01-01
        • 2013-04-13
        • 1970-01-01
        • 1970-01-01
        • 2021-08-27
        • 1970-01-01
        • 1970-01-01
        • 2022-12-05
        相关资源
        最近更新 更多