46

我第一次为 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 的“文件对话框”帮助部分,但也没有从那里收集任何东西。

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

4

4 回答 4

66

你得到的例外是告诉你filedialog不在你的命名空间中。 filedialog(和 btw 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()

在此处输入图像描述

于 2012-02-11T11:14:39.670 回答
3

我必须先指定单个命令,然后使用*将所有命令都带入命令。

from tkinter import filedialog
from tkinter import *
于 2015-09-17T12:54:44.407 回答
2

您是否尝试将 self 前缀添加到 fileName 并替换 Button 上方的方法?使用 self,它在方法之间变得可见。

...

def load_file(self):
    self.fileName = filedialog.askopenfilename(filetypes = (("Template files", "*.tplate")
                                                     ,("HTML files", "*.html;*.htm")
                                                     ,("All files", "*.*") ))
...
于 2012-02-11T10:52:03.070 回答
0

Tkinter is actually a python package, or a folder of python files. Check python source to find it. "tkinter.filedialog" is part of "tkinter.messagebox" Try "from tkinter.messagebox import filedialog" to get filedialog [python 3.7].

于 2021-07-06T20:38:17.230 回答