【发布时间】:2020-07-30 15:33:56
【问题描述】:
#标记 continue 语句。我想将控件带到 if-elif 条件的开头。这样如果用户在选择 csv 后选择 excel ,而不关闭退出窗口。标签在“根”窗口上相应更新。 #
# importing tkinter and tkinter.ttk and all their functions and classes
import tkinter
import tkinter.ttk
import os
import sys
import time
# importing askopenfile function from class filedialog
from tkinter.filedialog import askopenfile
root = tkinter.Tk()
root.geometry('400x200')
root.title("CR7 - GSM BSC - Automation Tool ")
label = tkinter.Label(root, text ="Please Select the CR7 Input file for Generating Scripts").pack#(side="top", pady=10)
# This function will be used to open file in read mode and only excel & csv can be opened
def open_file():
file = askopenfile(mode='r', filetypes=[('CSV Files', '*.csv'),('Excel 2003', '*.xls'),('Excel 2007', '*.xlsx')])
filepathstring = str(file)
if filepathstring.find("xls") > 1 or filepathstring.find("xlsx") > 1 and filepathstring.find("csv") <1 :
label1 = tkinter.Label(root, text="Selected file is 'Excel' File & will be converted to 'CSV' file ").pack(side="top",pady=40)
continue
elif filepathstring.find("xls") < 1 or filepathstring.find("xlsx") < 1 and filepathstring.find("csv") > 1 :
label2 = tkinter.Label(root, text="Selected file is 'csv' File ").pack(side="top", pady=20)
continue
btn = tkinter.Button(root, command=lambda: open_file(), text='Open').pack(side="top", pady=10)
root.mainloop()
【问题讨论】:
-
First
askopenfile()将返回一个打开的文件对象,而不是文件名。您应该改用askopenfilename()。其次,每次点击Open按钮只能选择一个文件,那么“选择csv后选择excel”是什么意思? -
感谢@acw1668 的第一个建议。是的,我的想法是一次选择一个文件。我想根据选择的文件在窗口中放置一个标签。但是如果以某种方式选择了错误的文件类型并决定在同一个文件对话框打开时选择另一个文件来更正它。然后发生错误......即第一次选择文件时打印的标签在切换到另一种文件类型时会保留。所以我想基本上重新启动循环以避免这个错误。
-
然后您应该在
open_file()之外创建消息标签,然后在函数内部更新其文本。但不要像label1 = tkinter.Label(...).pack(...)那样创建它,因为label1将是None。将语句分成两部分:label1 = tkinter.Label(...)和label1.pack(...)。
标签: python-3.x tkinter