Ics*_*ilk 37 python filedialog tkinter global-variables python-3.x
我正在第一次为Python3中的程序编写Browse按钮.我一直在搜索互联网和这个网站,甚至是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
Run Code Online (Sandbox Code Playgroud)
该方法是我在自己的自定义过程中发现的一些代码的混合体.好像我终于让它工作了(有点),虽然它不是我需要它的方式.
当我激活"浏览"按钮时出现此错误:NameError: global name 'filedialog' is not defined.
我一路上发现了类似的问题,但我已经介绍了所有解决方案.我进入了IDLE的'filedialog'帮助部分,但也没有从那里收集任何东西.
有人会介意提供一个细分和一点指导; 我的书都没有专门解决它,我已经检查了提供给其他人的所有解决方案 - 我输了.
joa*_*uin 60
您得到的例外是告诉您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
>>>
Run Code Online (Sandbox Code Playgroud)
你应该使用例如:
>>> from tkinter import filedialog
>>> filedialog
<module 'tkinter.filedialog' from 'C:\Python32\lib\tkinter\filedialog.py'>
>>>
Run Code Online (Sandbox Code Playgroud)
要么
>>> import tkinter.filedialog as fdialog
Run Code Online (Sandbox Code Playgroud)
要么
>>> from tkinter.filedialog import askopenfilename
Run Code Online (Sandbox Code Playgroud)
所以这适用于您的浏览按钮:
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()
Run Code Online (Sandbox Code Playgroud)

| 归档时间: |
|
| 查看次数: |
127464 次 |
| 最近记录: |