gpt4 book ai didi

python - 文件对话框、tkinter 和打开文件

转载 作者:IT老高 更新时间:2023-10-28 21:47:13 32 4
gpt4 key购买 nike

我第一次为 Python3 中的程序编写浏览按钮。我一直在搜索互联网和这个网站,甚至是 python 标准库。

我找到了示例代码和对事物的非常肤浅的解释,但我无法找到任何可以直接解决我遇到的问题的内容,或者找到足够好的解释,以便我可以根据需要自定义代码。

以下是相关片段:

Button(self, text = "Browse", command = self.load_file, width = 10)\
.grid(row = 1, column = 0, sticky = W) .....


def load_file(self):

filename = filedialog.askopenfilename(filetypes = (("Template files", "*.tplate")
,("HTML files", "*.html;*.htm")
,("All files", "*.*") ))
if filename:
try:
self.settings["template"].set(filename)
except:
messagebox.showerror("Open Source File", "Failed to read file \n'%s'"%filename)
return

该方法是我在此过程中发现的一些代码与我自己的自定义的混合体。看起来我终于让它工作了(有点),虽然它不完全是我需要的。

当我激活“浏览”按钮时出现此错误:NameError: global name 'filedialog' is not defined

在此过程中我发现了相当相似的问题,但我已经涵盖了所有建议的解决方案。我进入了 IDLE 的“文件对话框”帮助部分,但也没有从那里收集任何内容。

有人介意对此提供一个分割和一些指导吗?我的书都没有专门解决这个问题,我已经检查了提供给其他人的所有解决方案——我迷路了。

最佳答案

您得到的异常是告诉您 filedialog 不在您的命名空间中。filedialog (顺便说一句 messagebox)是一个 tkinter 模块,所以它不是只用 from tkinter import *

导入的
>>> from tkinter import *
>>> filedialog
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
NameError: name 'filedialog' is not defined
>>>

你应该使用例如:

>>> from tkinter import filedialog
>>> filedialog
<module 'tkinter.filedialog' from 'C:\Python32\lib\tkinter\filedialog.py'>
>>>

>>> import tkinter.filedialog as fdialog

>>> from tkinter.filedialog import askopenfilename

所以这对您的浏览按钮有用:

from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror

class MyFrame(Frame):
def __init__(self):
Frame.__init__(self)
self.master.title("Example")
self.master.rowconfigure(5, weight=1)
self.master.columnconfigure(5, weight=1)
self.grid(sticky=W+E+N+S)

self.button = Button(self, text="Browse", command=self.load_file, width=10)
self.button.grid(row=1, column=0, sticky=W)

def load_file(self):
fname = askopenfilename(filetypes=(("Template files", "*.tplate"),
("HTML files", "*.html;*.htm"),
("All files", "*.*") ))
if fname:
try:
print("""here it comes: self.settings["template"].set(fname)""")
except: # <- naked except is a bad idea
showerror("Open Source File", "Failed to read file\n'%s'" % fname)
return


if __name__ == "__main__":
MyFrame().mainloop()

enter image description here

关于python - 文件对话框、tkinter 和打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9239514/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com