![](/img/trans.png)
[英]Retrieving attribute from checkbuttons - Tkinter, checkbuttons, python
[英]Python Tkinter: Reading in file from location, creating checkbuttons for each file
我正在嘗試從PC上的文件夾位置讀取文本文件。 然后為每個文件創建檢查按鈕。 選中復選框后,我想按“提交”以打印在控制台窗口中選擇的每個文件。
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()
根據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現在看起來像:
def ShowChoice():
print [button.attached_file for button in buttons if button.get()]
如果選中每個按鈕,則為每個按鈕打印附件文件(button.attached_file)(如果選中,則button.get()為1)。
不要忘記在所有這些東西之前聲明“ buttons = []”。
您也可以閱讀並采用PEP8作為樣式,以更具可讀性的文件(適合所有人)結尾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.