我正在玩tkinter,我想把它应用到我试图解决的问题上。基本代码基于在 https://docs.python.org/3/library/tkinter.html 的“A Simple Hello World Program”下找到的教程。我正在更改为一个目录,创建该目录的列表,并根据在那里找到的文件创建检查按钮。当我当前检查或取消选中其中一个检查按钮时,它会将“嗨,大家好!”打印到控制台。
假设 os.listdir() 返回: my_list = [file1, file2, file3, file4, file5]
最终我想得到一个字典,其中包含文件名和检查按钮的状态,如下所示:
my_dict{file1:1, file2:0, file3:0, file4:1, file5:1}.
我还需要实时更新它,直到程序结束。
如果我手动单独创建每个检查按钮,我可以执行此操作,但是文件的数量会不时更改,我宁愿每次添加或删除文件时都不必回来更改我的脚本。
我如何获取每个生成的检查按钮的变量,并在选中/取消选中时随时更新字典中的该值?
import tkinter as tk
import os
os.chdir('c:\\some\\path\\here')
my_list = os.listdir()
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
for filename in my_list:
var = tk.IntVar()
self.filename = tk.Checkbutton(self, text=filename, variable=var, command=self.check_state)
self.items[filename] = var #this is where i'm getting the 'application has no member' error
self.filename.pack(side="top")
self.quit = tk.Button(self, text="Cancel",
command=self.master.destroy)
self.quit.pack(side="bottom")
def check_state(self):
my_dict = {filename:self.items[filename].get() for filename in self.items} #getting the same 'application has no member' error here as well
print(my_dict)
root = tk.Tk()
app = Application(master=root)
app.mainloop()
繁花如伊
相关分类