PythonTkinter:从位置读入文件,为每个文件创建复选按钮

PythonTkinter:从位置读入文件,为每个文件创建复选按钮,python,tkinter,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)

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

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()
运行此代码后,结果是当选中任何检查按钮并选择提交按钮时,只打印文件夹中的最后一个文本文件。这对我来说很有意义,因为文件被保存为读取的最后一个文件。但是,我想不出存储每个文件名的方法。除非我把文件读入一个数组,我也不知道该怎么做。 非常感谢任何帮助

除非我把文件读入数组

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

但若您列出了一个复选按钮及其相关变量的列表,那个就太好了。这样,您就可以在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()
根据,您必须将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

不要忘记在所有这些东西之前声明一个按钮=[]

您还可以阅读并采用for样式,以一个更具可读性的for Everyone文件结束