天天看点

python使用tkinter可以在多个操作系统_使用tkinter选择多个文本文件后,如何同时打开和操作它们?...

您没有使用列表中的每个文件名。因此,您需要在创建自的列表上运行for循环。

askopenfilenames()

.

根据我的IDE中的工具提示

askopen文件名()

返回一个列表。

def askopenfilenames(**options):

"""Ask for multiple filenames to open

Returns a list of filenames or empty list if

cancel button selected

"""

options["multiple"] = 1

return Open(**options).show()

我把变量文件名改成了文件名,因为它是一个列表,这更有意义。然后我在这个列表上运行了一个for循环,它应该可以根据需要工作。

尝试下面的代码。

import re

from Tkinter import *

from tkFileDialog import askopenfilenames

filenames = askopenfilenames()

for filename in filenames:

f = open(filename, "r")

lines = f.readlines()

f.close()

f = open(filename, "w")

for line in lines:

line = re.sub('', "", line)

f.write(line)

f.close()

通过几个if语句,我们可以防止在不选择任何内容或选择不兼容的文件类型时可能出现的最常见错误。

import re

from Tkinter import *

from tkFileDialog import askopenfilenames

filenames = askopenfilenames()

if filenames != []:

if filenames[0] != "":

for filename in filenames:

f = open(filename, "r")

lines = f.readlines()

f.close()

f = open(filename, "w")

for line in lines:

line = re.sub('', "", line)

f.write(line)

f.close()