亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python Tkinter - 使用命令功能

Python Tkinter - 使用命令功能

慕斯709654 2022-08-25 14:53:19
我正在玩tkinter,我想把它應用到我試圖解決的問題上?;敬a基于在 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 關注
  • 94 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號