错误处理以确保仍可访问文件

时间:2018-06-19 19:47:05

标签: python python-3.x tkinter

我正在为使用Tkinter工作的医院创建数字标牌。通过读取保存到共享网络驱动器并在另一台计算机上编辑的文本文件的内容,以反映当前延迟,从而使患者了解当前延迟。

我遇到的问题是,在候诊室中运行的计算机似乎间歇性连接问题,当我的脚本尝试访问网络上存储的文件时会导致错误。重新建立连接后,由于错误,它会继续运行,但只是坐在那里而不更新文本文件的延迟。

在尝试再次运行功能之前,我尝试使用try和error处理来添加time.sleep,但是我认为我做的不正确。

我的代码可能是一团糟,但我希望它足够清楚。

import tkinter as tk
from PIL import Image, ImageTk
from itertools import cycle
from os import listdir
from docx import Document
import os

welcome_message = "Welcome to the Varian Waiting Room"
frequency = 30000
x = 1200
y = 800
areas = ["varian 1", "varian 2"]
fontSize = 30


class App(tk.Tk):
    slides = [slide for slide in listdir("slides") if slide.endswith('jpg')]
    label_id_list = []
    label_name_list = []

def __init__(self):
    tk.Tk.__init__(self)
    self.attributes('-fullscreen', True)
    self.top = tk.Frame(self, bg="skyblue1")
    self.middle = tk.Frame(self)
    self.middleLeft = tk.Frame(self.middle)
    self.middleRight = tk.Frame(self.middle)
    self.initialise()
    self.check_delay()
    self.find_slides()
    self.show_slides()
    self.show_announcements()

def initialise(self):
    self.top.grid(row=0, rowspan=1, columnspan=3, sticky="nsew")
    self.middle.grid(row=1, rowspan=2, columnspan=5, sticky="nsew")
    self.middleLeft.grid(row=1, rowspan=2, column=0, columnspan=3, sticky="nsew")
    self.middleRight.grid(row=1, rowspan=2, column=4, columnspan=3, sticky="nsew")
    self.grid_rowconfigure(1, weight=1)
    self.grid_columnconfigure(1, weight=1)
    self.middle.columnconfigure(4, weight=1)
    self.top_bar()
    self.middle_left_section()
    self.middle_right_section()

def top_bar(self):
    self.welcome = tk.Label(self.top, bg="skyblue1", fg="white", text=welcome_message,
                            font=("", 40, "italic", "bold"))
    self.welcome.pack(side="right", fill="both", expand=True)
    self.nhs = Image.open(os.path.join("config", "logo.png"))
    self.icon = ImageTk.PhotoImage(self.nhs)
    self.logo = tk.Label(self.top, image=self.icon, bg="skyblue1")
    self.logo.pack(side="left", fill="both", expand=False, padx=50, pady=20)

def middle_left_section(self):
    self.picture_display = tk.Label(self.middleLeft, bg="white")
    self.picture_display.pack(fill="both", expand=False, padx=60, pady=30)
    self.pictures = cycle(
        (ImageTk.PhotoImage(Image.open(os.path.join("slides", image)).resize((x, y), Image.ANTIALIAS)), image) for
        image in self.slides)

def middle_right_section(self):
    self.title = tk.Label(self.middleRight, text="Machine delays", font=("", 30, "italic", "bold"), padx=30,
                          pady=30)
    self.title.pack(fill="both", expand=False, side="top")

    self.create_delay_labels()

    self.title2 = tk.Label(self.middleRight, text="Announcements", font=("", 30, "italic", "bold"))
    self.title2.pack(fill="both", expand=False, side="top", padx=30, pady=30)

    self.announcement = tk.Message(self.middleRight, text="", font=("", 20, "bold"), width=400)
    self.announcement.pack(fill="both", expand="False", side="top")

def create_delay_labels(self):
    for area in areas:
        name = tk.Label(self.middleRight, text=area.title(), font=("", 25, ""))
        name.pack(side="top", fill="both", expand=False)
        self.label_name_list.append(area)
        self.label_id_list.append(name)

def find_slides(self):
    """Searches for jpg files. If it finds new files it replaces the self.slides list"""
    rescan_slides = [slide for slide in listdir("slides") if slide.endswith('jpg')]

    if rescan_slides != self.slides:
        self.slides = None
        self.pictures = None
        self.slides = rescan_slides
        self.pictures = cycle(
            (ImageTk.PhotoImage(Image.open(os.path.join("slides", image)).resize((x, y), Image.ANTIALIAS)), image)
            for
            image in self.slides)
    self.after(30000, self.find_slides)

def show_slides(self):
    img_object, img_name = next(self.pictures)
    self.picture_display.config(image=img_object)
    self.after(frequency, self.show_slides)

def show_announcements(self):
    annon = self.read_announcements()
    if not annon:
        annon = "There are no announcements to display"
    self.announcement.configure(text=annon)
    self.after(30000, self.show_announcements)

def read_announcements(self):
    doc = Document("announcements.docx")
    fullText = []
    for para in doc.paragraphs:
        fullText.append(para.text)
    return '\n'.join(fullText)

def check_delay(self):
    for name in self.label_id_list:
        index = self.label_id_list.index(name)
        location = self.label_name_list[index]
        path = os.path.join("config", f"{location}.txt")
        with open(path, "rt") as in_file:
                contents = in_file.read()
                if not contents or contents == "0":
                    name.config(text=f"{location.title()} is on time", foreground="green",
                                font=("", fontSize, "bold"))
                elif contents.isdigit():
                    name.config(text=f"{location.title()} is {contents} minutes delayed", foreground="red",
                                font=("", fontSize, "bold"))
                elif 'service' in contents:
                    name.config(text=f"{location.title()} is being serviced", foreground="red",
                                font=("", fontSize, "bold"))
                else:
                    name.config(text=f"null", foreground="black",
                                font=("", fontSize, "bold"))
    self.after(5000, self.check_delay)

def run(self):
    self.mainloop()


app = App()
app.run()

给出的错误也包括在下面。

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python 32bit\lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
  File "C:\Python 32bit\lib\tkinter\__init__.py", line 745, in callit
    func(*args)
  File "varian_display.py", line 121, in check_delay
OSError: [Errno 22] Invalid argument
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python 32bit\lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
  File "C:\Python 32bit\lib\tkinter\__init__.py", line 745, in callit
    func(*args)
  File "varian_display.py", line 84, in find_slides
FileNotFoundError: [WinError 53] The network path was not found: 'slides'
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python 32bit\lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
  File "C:\Python 32bit\lib\tkinter\__init__.py", line 745, in callit
    func(*args)
  File "varian_display.py", line 97, in show_slides
  File "varian_display.py", line 60, in <genexpr>
  File "C:\Python 32bit\lib\site-packages\PIL\Image.py", line 2543, in open
    fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'slides\\Radiographers.jpg'
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python 32bit\lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
  File "C:\Python 32bit\lib\tkinter\__init__.py", line 745, in callit
    func(*args)
  File "varian_display.py", line 102, in show_announcements
  File "varian_display.py", line 109, in read_announcements
  File "C:\Python 32bit\lib\site-packages\docx\api.py", line 25, in Document
    document_part = Package.open(docx).main_document_part
  File "C:\Python 32bit\lib\site-packages\docx\opc\package.py", line 116, in open
    pkg_reader = PackageReader.from_file(pkg_file)
  File "C:\Python 32bit\lib\site-packages\docx\opc\pkgreader.py", line 32, in from_file
    phys_reader = PhysPkgReader(pkg_file)
  File "C:\Python 32bit\lib\site-packages\docx\opc\phys_pkg.py", line 31, in __new__
    "Package not found at '%s'" % pkg_file
docx.opc.exceptions.PackageNotFoundError: Package not found at 'announcements.docx'

0 个答案:

没有答案