pythontkinter:从位置读取文件,为每个fi创建复选按钮

2024-10-02 20:41:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从我电脑上的文件夹位置读入文本文件。然后为每个文件创建复选按钮。在选择了复选按钮后,我想按“提交”来打印控制台窗口中选择的每个文件。在

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()

运行此代码后,结果是当选中任何复选按钮并选中“提交”按钮时,只打印文件夹中的最后一个文本文件。这对我来说很有意义,因为文件是作为最后一个被读入的文件保存的。但是,我想不出存储每个文件名的方法。除非我把文件读入一个数组,我也不知道该怎么做。 非常感谢任何帮助!在


Tags: 文件textimport文件夹ifosroot按钮
2条回答

Unless maybe I read files into an array

不,您不希望一次读取所有这些文件。这将极大地影响性能。在

但是如果你列一个checkbutton和它们相关联的变量的列表就好了。这样,您就可以在函数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()

根据the checkbutton doc,必须将一个IntVar绑定到按钮,才能查询其状态。在

因此,在构建按钮时,给它们一个IntVar,欺骗并将文件名附加到IntVar,以便稍后获取:

checked = IntVar()
checked.attached_file = file
aCheckButton = Checkbutton(root, text=file, variable=checked)
aCheckButton.pack(anchor=W)
buttons.append(checked)

您的ShowChoice现在看起来像:

^{pr2}$

打印附加文件(button.attached_文件)对于每个按钮,如果选中该按钮(按钮。获取()为1(如果选中)。在

别忘了在所有这些东西之前声明一个“buttons=[]”。在

您还可以阅读并采用样式的PEP8,以一个可读性更强的(对所有人来说)文件结尾。在

相关问题 更多 >