当用户单击“取消"时,Tkinter askopenfilename 未按预期返回. [英] Tkinter askopenfilename not returning as expected when user clicks "Cancel."

查看:30
本文介绍了当用户单击“取消"时,Tkinter askopenfilename 未按预期返回.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据文档,如果用户单击取消",filedialog.askopenfilename() 应该返回一个空字符串,但它没有这样做,我无法弄清楚它实际返回的是什么.

According to the documentation, filedialog.askopenfilename() is supposed to return an empty string if the user clicks "Cancel," but it's not doing that, and I can't figure out what it's actually returning.

我制作了这个小测试程序,其行为与我的实际项目相同:

I made this little test program, and the behavior is identical to my actual project:

from tkinter import *
from tkinter import filedialog

name = filedialog.askopenfilename()
if name == '':
    print("Nothing chosen")
else:
    print(name)

当用户点击取消时最终打印的是一对空括号 ()

What ends up printing when the user clicks cancel is a pair of empty parentheses ()

用 '()' 替换 '' 不会改变任何东西.

Replacing '' with '()' does not change anything.

任何帮助弄清楚正在发生的事情的帮助都表示赞赏.谢谢.

Any help figuring out what is happening is appreciated. Thank you.

更新:感谢@PaulRooney 的建议,让它工作起来,但是现在,我第一次运行这部分代码(在我的完整项目中)时,它返回空元组.对于后续的每次运行,它都会返回一个空字符串.

UPDATE: Got it working thanks to @PaulRooney's suggestion, but now, the first time I run this section of code (in my full project), it returns the empty tuple. For every subsequent run, it returns an empty string.

简单地检查两者都能满足我的需要,但这是一种奇怪的行为.

Simply checking for both works for what I need, but it's bizarre behavior.

我在 Linux Mint 上使用 Python 3.

I'm using Python 3 on Linux Mint.

推荐答案

if name 就可以了.

if name will work just fine.

from tkinter import *
from tkinter import filedialog

name = filedialog.askopenfilename()
if name:
    print(name)
else:
    print("Nothing chosen")

这篇关于当用户单击“取消"时,Tkinter askopenfilename 未按预期返回.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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