【问题标题】:How to prevent opening an already open file using Python/tkinter [closed]如何防止使用 Python/tkinter 打开已经打开的文件 [关闭]
【发布时间】:2015-05-20 04:39:47
【问题描述】:

对不起,如果这是一个愚蠢的问题......但我是学习 Python 的新手,这是一个家庭作业问题......

所以我想阻止人们使用 tkinter 重新打开已加载的文件 - 并在他们尝试打开文件时弹出错误对话框。

到目前为止,我得到了这个:

from tkinter import filedialog
from tkinter import messagebox

def open_file(self):
    openfiles=[]
    filename = filedialog.askopenfilename(filetypes=[("allfiles","*.txt")])

    if filename not in openfiles:
        openfiles.append(filename)
        self._filename = filename
        functiontoloadfile(filename)

    else:
        messagebox.showerror(filename + "is already open")

【问题讨论】:

  • open_file 在类内吗?
  • 是的,它在课堂内 - 抱歉我没有提到
  • 您的问题是什么?您已经告诉我们您想要什么以及您拥有什么,但没有告诉我们您遇到了什么问题。

标签: python tkinter


【解决方案1】:

假设 open_files() 是一个不在类内部的函数,您可以像这样持久化您的 openfiles 列表:

openfiles=[]
def open_file(self):
    filename = filedialog.askopenfilename(filetypes=[("allfiles","*.txt")])

    if filename not in openfiles:
        openfiles.append(filename)
        functiontoloadfile(filename)
    else:
        messagebox.showerror(filename + "is already open")

这将使您的openfiles 列表在open_file 函数的多次调用中保持不变。当然,您需要确保在文件关闭时从该列表中删除,这可能会让人有点头疼。

一种更好的方法可能是,您可以检测哪些 UI 元素正在显示文件,并根据这些 UI 元素的存在推断文件是否打开。

【讨论】:

    【解决方案2】:

    在 python 中,如果您尝试打开一个已经打开的文件,您可能会引发如下错误:

    try:
        myfile = open("myfile.csv", "r+") # or "a+", whatever you need
    except IOError:
        print "Is already open"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多