为了账号安全,请及时绑定邮箱和手机立即绑定

Python Tkinter - 使用命令功能

Python Tkinter - 使用命令功能

慕斯709654 2022-08-25 14:53:19
我正在玩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 tkimport osos.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()
查看完整描述

1 回答

?
繁花如伊

TA贡献2012条经验 获得超12个赞

您可以使用 带文件名 的 键和值,然后在 中生成所需的值:dictIntVardictcheck_state()


def create_widgets(self):

    self.items = {}   # holds filename:IntVar

    for filename in my_list:

        var = tk.IntVar()

        cb = tk.Checkbutton(self, text=filename, variable=var, command=self.check_state)

        cb.pack(side="top")

        self.items[filename] = var


    self.quit = tk.Button(self, text="Cancel", command=self.master.destroy)

    self.quit.pack(side="bottom")


def check_state(self):

    print("hi there, everyone!")

    my_dict = {filename:self.items[filename].get() for filename in self.items}

    print(my_dict)

    # or use self.my_dict if it is used by other instance functions


查看完整回答
反对 回复 2022-08-25
  • 1 回答
  • 0 关注
  • 111 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号