gpt4 book ai didi

Python3 askopenfilename错误

转载 作者:行者123 更新时间:2023-11-28 21:52:28 24 4
gpt4 key购买 nike

我正在为 volatility 框架的 GUI 基础编写 python 程序,我仍处于初始阶段,因为我是 python 的初学者,我正在使用从“askopnefilename”导入的文件,该函数在我打开和关闭时出错没有选择文件,所以你能帮我解决吗?

代码:

from tkinter import *
from tkinter import filedialog
from tkinter.filedialog import askopenfilename
from mtTkinter import *
import subprocess


def donothing():
filewin = Toplevel(root)
button = Button(filewin, text="Do nothing button")
button.pack()

def OpenFile():
file = open(askopenfilename(),'r')
print(root.file)

def Quit():
root.destroy()

def Test():
print("Hello world")
input("Press return to exit")

def Shell():
# print("Below is the output")
subprocess.call('./home/shanaka/bash_lerning/function1.sh',shell=True)


root = Tk()
root.title("Volatility")
root.geometry("600x400")

menubar = Menu(root)
startmenu = Menu(menubar, tearoff=0)
startmenu.add_command(label="Import", command=OpenFile)
startmenu.add_separator()
startmenu.add_command(label="Exit", command=Quit)
menubar.add_cascade(label="Start", menu=startmenu)

searchmenu = Menu(menubar, tearoff=0)

submenu = Menu(searchmenu)
submenu.add_command(label="New feed", command=Shell)
submenu.add_command(label="Bookmarks")
submenu.add_command(label="Mail")
searchmenu.add_cascade(label='Plugins', menu=submenu, underline=0)

searchmenu.add_separator()
#searchmenu.add_command(label="Plugins", command=Test)
searchmenu.add_command(label="Copy", command=donothing)
searchmenu.add_command(label="Paste", command=donothing)
searchmenu.add_command(label="Delete", command=donothing)
searchmenu.add_command(label="Select All", command=donothing)
menubar.add_cascade(label="Search", menu=searchmenu)

reportmenu = Menu(menubar, tearoff=0)
reportmenu.add_command(label="Generate Reports", command=donothing)
menubar.add_cascade(label="Reports", menu=reportmenu)


helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="Help Index", command=donothing)
helpmenu.add_command(label="About...", command=donothing)
menubar.add_cascade(label="Help", menu=helpmenu)

root.config(menu=menubar)
root.mainloop()

错误如下

Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.4/tkinter/__init__.py", line 1490, in __call__
return self.func(*args)
File "/home/shanaka/Project1.py", line 13, in OpenFile
file = open(askopenfilename(),'r')
FileNotFoundError: [Errno 2] No such file or directory: ''

最佳答案

仅当 askopenfilename 返回非假值时才打开文件:

def OpenFile():
filepath = askopenfilename()
if filepath:
file = open(filepath, 'r')
...

顺便说一句,代码没有分配root.file;访问 root.file 将引发 AttributeError

关于Python3 askopenfilename错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28261876/

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