本文介绍了文件对话框、tkinter 和打开文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次为 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 = (("模板文件", "*.tplate"),("HTML 文件", "*.html;*.htm"),(所有文件", "*.*") ))如果文件名:尝试:self.settings["template"].set(filename)除了:messagebox.showerror("打开源文件", "读取文件失败
'%s'"%filename)返回

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

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

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

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

解决方案

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

导入的>>>从 tkinter 导入 *>>>文件对话框回溯(最近一次调用最后一次):文件<交互式输入>",第 1 行,在 <module> 中NameError: 名称 'filedialog' 未定义>>>

你应该使用例如:

>>>从 tkinter 导入文件对话框>>>文件对话框<来自'C:Python32libkinterfiledialog.py'的模块'tkinter.filedialog'>>>>

>>>将 tkinter.filedialog 导入为 fdialog

>>>从 tkinter.filedialog 导入 askopenfilename

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

from tkinter import *从 tkinter.filedialog 导入 askopenfilename从 tkinter.messagebox 导入 showerror类 MyFrame(Frame):def __init__(self):Frame.__init__(self)self.master.title("例子")self.master.rowconfigure(5, weight=1)self.master.columnconfigure(5, weight=1)self.grid(粘性=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=(("模板文件", "*.tplate"),("HTML 文件", "*.html;*.htm"),(所有文件", "*.*") ))如果 fname:尝试:打印("""它来了:self.settings["template"].set(fname)""")除外:# <- 裸体除外是个坏主意showerror("打开源文件", "读取文件失败
'%s'" % fname)返回如果 __name__ == "__main__":MyFrame().mainloop()

I'm working for the first time on coding a Browse button for a program in Python3. I've been searching the internet and this site, and even python standard library.

I have found sample code and very superficial explanations of things, but I haven't been able to find anything that addresses the problem I'm having directly, or a good enough explanation so I can customize code to my needs.

Here is the relevant snippet:

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
'%s'"%filename)
            return

The method is a hybrid of some code I found along the way with my own customizations. It seems like I finally got it to work (kinda), though its not exactly how I need it.

I get this error when I activate the 'Browse' button: NameError: global name 'filedialog' is not defined.

I've found fairly similar issues along the way but all the solutions suggested I have covered. I went into the 'filedialog' help section of IDLE but didn't glean anything from there either.

Would someone mind providing a break down and a little guidance on this; none of my books address it specifically, and I've checked all the solutions provided to others—I'm lost.

解决方案

The exception you get is telling you filedialog is not in your namespace.filedialog (and btw messagebox) is a tkinter module, so it is not imported just with 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
>>>

you should use for example:

>>> from tkinter import filedialog
>>> filedialog
<module 'tkinter.filedialog' from 'C:Python32lib	kinterfiledialog.py'>
>>>

or

>>> import tkinter.filedialog as fdialog

or

>>> from tkinter.filedialog import askopenfilename

So this would do for your browse button:

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
'%s'" % fname)
            return


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

这篇关于文件对话框、tkinter 和打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 08:41