Python Tkinter:从指定位置读取文件,为每个文件创建复选框
我想从我电脑上的一个文件夹里读取文本文件。然后为每个文件创建一个复选框。选择好复选框后,我想按“提交”按钮,把每个选中的文件在控制台窗口打印出来。
from Tkinter import *
#Tk()
import os
root = Tk()
v = StringVar()
v.set("null") # initializing the choice, i.e. Python
def ShowChoice():
state = v
if state != 0:
print(file)
for file in os.listdir("Path"):
if file.endswith(".txt"):
aCheckButton = Checkbutton(root, text=file, variable= file)
aCheckButton.pack(anchor =W)
v = file
print (v)
submitButton = Button(root, text="Submit", command=ShowChoice)
submitButton.pack()
mainloop()
运行这段代码后,结果是当我选中任何复选框并点击提交按钮时,控制台只打印出文件夹里的最后一个文本文件。我明白为什么会这样,因为程序只保存了最后一个读取的文件名。不过,我想不出有什么办法可以存储每个文件的名字。除非我把文件名读进一个数组,但我也不太确定该怎么做。希望能得到一些帮助!
2 个回答
0
根据checkbutton的文档,你需要把一个IntVar绑定到按钮上,这样才能查询它的状态。
所以在创建按钮的时候,给它们一个IntVar,稍微“作弊”一下,把文件名附加到这个IntVar上,这样以后就能获取到文件名:
checked = IntVar()
checked.attached_file = file
aCheckButton = Checkbutton(root, text=file, variable=checked)
aCheckButton.pack(anchor=W)
buttons.append(checked)
你的ShowChoice现在看起来是这样的:
def ShowChoice():
print [button.attached_file for button in buttons if button.get()]
如果按钮被选中(按钮的状态是1),就打印出附加的文件(button.attached_file)。
别忘了在这些内容之前声明一个“buttons = []”。
你也可以参考PEP8的风格指南,这样可以让你的代码更易读(大家都能看懂)。
0
除非我把文件读入一个数组里
不,你不想一次性读取所有这些文件。这会严重影响性能。
不过,如果你能把复选框和它们对应的变量列个清单,那就很好了。这样,你在函数 ShowChoice
里面就能轻松访问它们。
下面是你程序的一个版本,采用了这个思路。我对大部分修改的地方做了注释:
from Tkinter import *
import os
root = Tk()
# A list to hold the checkbuttons and their associated variables
buttons = []
def ShowChoice():
# Go through the list of checkbuttons and get each button/variable pair
for button, var in buttons:
# If var.get() is True, the checkbutton was clicked
if var.get():
# So, we open the file with a context manager
with open(os.path.join("Path", button["text"])) as file:
# And print its contents
print file.read()
for file in os.listdir("Path"):
if file.endswith(".txt"):
# Create a variable for the following checkbutton
var = IntVar()
# Create the checkbutton
button = Checkbutton(root, text=file, variable=var)
button.pack(anchor=W)
# Add a tuple of (button, var) to the list buttons
buttons.append((button, var))
submitButton = Button(root, text="Submit", command=ShowChoice)
submitButton.pack()
mainloop()