【问题标题】:tk.messagebox.showerror() appears in wrong conditiontk.messagebox.showerror() 出现错误情况
【发布时间】:2021-03-30 21:26:23
【问题描述】:

我在下面得到了这段代码,无论我在哪里选择一个 csv 文件,messagebox.showerror 函数都会激活,而它不应该激活。有任何想法吗?当我上传 xlsx 或 xls 文件时,它可以完美运行。

我想确保用户只上传 .csv 或 .xls 或 .xlsx 文件,为此我尝试使用 ifs 进行一些错误处理。如果逻辑会出错吗?可能是字符串问题吗?我检查了类型并打印了文件类型变量,它给出了 csv。

import pandas as pd
import matplotlib.pyplot as plt
import tkinter as tk
import tkinter.filedialog



#######################################################################################################
##### FUNCTIONS
#######################################################################################################
df_root= False
df= False
Error = None

def openfile():
    global df_root
    df_root = tk.filedialog.askopenfilename(initialdir="C:",
                           filetypes =(("All Files","*.*"),[("Excel Files",".xlsx .xls"),("CSV Files",".csv")]),
                           title = "Choose a file.")
    filetype= df_root.split(".")[1]
    print(filetype)

    global df

    if filetype == "csv":   
        df=pd.read_csv(df_root)
    if filetype =="xlsx" or filetype=="xls":
        df=pd.read_excel(df_root)
    else:
        tk.messagebox.showerror("Filetype Error","The selected file must be: .csv .xls or .xlsx")
        df= False
# Create the Root tkinter object
root = tk.Tk()


##### - Screen Size Options

# Get Screen width and Height
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
screen_ratio = round(screen_width/screen_height,1)
# Set root to zoomed state
root.state("zoomed")

# Set the root mainloop to keep the program open
root.mainloop()

【问题讨论】:

  • 你为什么有("All Files", "*.*")?在你的例子中,你也从来没有真正打电话给openfile
  • @TheLizzard:("All Files", "*.*") 是一个非常常见的文件对话框习语。它使用户有机会打开任何文件,而不仅仅是带有预定义后缀的文件。
  • 非常感谢,所以为了避免所有这些错误处理,我根本不允许用户加载任何其他内容。
  • @BryanOakley 来自 OP 的问题:“我想确保用户只上传 .csv 或 .xls 或 .xlsx 文件”。这就是为什么我认为 OP 并不真正需要 "*.*"
  • @TheLizzard:“一个 csv 文件”有点模棱两可。您可以拥有一个名为“my_data.txt”的文件,它是一个 csv 文件。文件是 csv 文件这一事实与文件名无关,正如可能有一个名为“my_data.csv”的文件不是为 csv 格式。软件的存在是为了为用户服务,限制他们的选择并不总是对用户最友好的事情。

标签: string csv tkinter openfiledialog


【解决方案1】:

如果您使用.csv 文件来测试您的代码并且遇到此错误,我相信您的错误在于:

if filetype =="xlsx" or filetype=="xls":

应该是:

elif filetype =="xlsx" or filetype=="xls":

因为如果是.csvif filetype =="xlsx" or filetype=="xls": 将不会通过,因此会引发错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 2017-01-11
    • 2020-03-18
    • 2017-12-19
    相关资源
    最近更新 更多