在 Tkinter 中使用按钮调用函数后返回值 [英] Returning a value after calling a function with a button in Tkinter

查看:52
本文介绍了在 Tkinter 中使用按钮调用函数后返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 库制作一个成像程序.我需要在上面的代码中做的是返回存储在文件名中的字符串,因此它在程序的全局范围内,我可以使用它.问题是我不知道如何在使用按钮调用函数时执行此操作.我在任何网站上都找不到这个问题的答案,所以我很感激任何人对这个问题的帮助.

I am kind of a newbie at programming in general, but I am trying to make an imaging program through the Tkinter GUI library. What I need to be able to do in the code above is return the string that is stored in filename so it is in the global scope of the program and I am able to use it. The problem is I don't know how to do this when calling the function with a button. I cannot find the answer to this problem on any website so I would appreciate anybody's help with this problem.

推荐答案

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

Generally, it is bad practice to use global variables to pass information around your program. However, if you really must do this, use a mutable data type (such as a list or a dict) as your global variable and change its contents from your callback function, 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.

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

If you intend to do this frequently, consider implementing your own class to pass information around.

这篇关于在 Tkinter 中使用按钮调用函数后返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆