我试图从我电脑上的文件夹位置读入文本文件。然后为每个文件创建复选按钮。在选择了复选按钮后,我想按“提交”来打印控制台窗口中选择的每个文件。在
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()
运行此代码后,结果是当选中任何复选按钮并选中“提交”按钮时,只打印文件夹中的最后一个文本文件。这对我来说很有意义,因为文件是作为最后一个被读入的文件保存的。但是,我想不出存储每个文件名的方法。除非我把文件读入一个数组,我也不知道该怎么做。 非常感谢任何帮助!在
不,您不希望一次读取所有这些文件。这将极大地影响性能。在
但是如果你列一个checkbutton和它们相关联的变量的列表就好了。这样,您就可以在函数
ShowChoice
中轻松地访问它们。在下面是一个采用这种想法的程序版本。我评论了我改的大部分台词:
根据the checkbutton doc,必须将一个IntVar绑定到按钮,才能查询其状态。在
因此,在构建按钮时,给它们一个IntVar,欺骗并将文件名附加到IntVar,以便稍后获取:
您的ShowChoice现在看起来像:
^{pr2}$打印附加文件(button.attached_文件)对于每个按钮,如果选中该按钮(按钮。获取()为1(如果选中)。在
别忘了在所有这些东西之前声明一个“buttons=[]”。在
您还可以阅读并采用样式的PEP8,以一个可读性更强的(对所有人来说)文件结尾。在
相关问题 更多 >
编程相关推荐