Tkinter python:关闭窗口后,有没有办法保存checkbutton变量的状态?

2024-10-02 00:26:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我是tkinter的新手,我想做的是:

  • 打开文件对话框窗口以选择文本文件。(已完成)
  • 处理文件的信息。(已完成)
  • 在tkinter窗口中显示文件的某些信息。(已完成)
  • 用户从上一个tkinter窗口中选择一些复选框,然后关闭该窗口,稍后代码中将使用复选框中的信息。(不工作)

这是我的代码,可能不是管理tkinter东西的最佳方法

# Import tkinter for file/directory dialogs.
from tkinter import *

# Definition of the structure of file's regions
# Just want to keep titles and subtitles in this part.
class SectionHeaders:
    def __init__(self, title, subtitles = []):
        self.title = title
        self.subtitles = subtitles

class CheckboxesMap():
    # fileSections is a list of SectionHeaders objects.
    def __init__(self, parent=None, fileSections=[]):
        # List of variables for each checkbox.
        self.vars = []
        # Helper variable
        r = 0
        for fileSection in fileSections:
            # Variable and checkbox for the title.
            var = IntVar()
            chk = Checkbutton(parent, text=fileSection.title, variable=var)
            chk.grid(row = r, column = 0, sticky = W)
            self.vars.append(var)
            r+=1
            for subtitle in fileSection.subtitles:
                var = IntVar()
                chk = Checkbutton(parent, text=subtitle, variable=var)
                chk.grid(row = r, column = 1, sticky = W)
                self.vars.append(var)
                r+=1

    def get_states(self):
        return map((lambda var: var.get()), self.vars)

# Function to run at the second tkinter window closing.
def closing_action(something, tkinstance=None):
    if tkinstance != None:
        tkinstance.destroy()
    if isinstance(something, CheckboxesMap):
        print(list(something.get_states()))

def main():
    # Creating instance of Tk, initializing tcl/tk interpreter.
    # We need to create this Tk instance and withdraw it in order to
    # initialize the interpreter.
    root = Tk()
    # Avoiding to keep the Tk window open, withdraw hides it.
    root.withdraw()

    ##### Some processing of the file content #####
    ## titles variable referenced below is a list
    ## of SectionHeaders objects.
    ## Added as part of EDIT 1.
    titles = []
    titles.append(SectionHeaders('Title 1', []))
    titles.append(SectionHeaders('Title 2', ['Subtitle 2.1', 'Subtitle 2.2']))
    titles.append(SectionHeaders('Title 3', ['Subtitle 3.1']))

    # Creating a selection tool with the titles listed.
    title_window = Tk()
    tk_titles = CheckboxesMap(title_window, titles)

    # The following three commands are needed so the window pops
    # up on top on Windows...
    title_window.iconify()
    title_window.update()
    title_window.deiconify()

    title_window.protocol("WM_DELETE_WINDOW", closing_action(tk_titles, root))
    title_window.mainloop()

    # Obtaining variable states
    print(list(tk_titles.get_states()))

Second Tkinter window

即使按照图中的选择,我在控制台中也会看到以下内容: [0,0,0,0,0,0,0,0,0]

关于如何在tkinter窗口关闭后保持这些值,有什么想法吗?我在处理tkinter材料方面有哪些改进

编辑1:添加了可用于示例的标题列表。 编辑2:保留最少的代码示例


Tags: ofthetoselffortitletkintervar
2条回答

我找到了问题的解决办法。这是因为您没有为IntVar指定父级。
只需更改即可

var = IntVar()

var = IntVar(parent)

我注意到的另一个问题(我想这不是故意的)是,当窗口关闭时调用的函数在程序运行时立即被调用。要修复此问题,请将title_window.protocol行更改为

title_window.protocol("WM_DELETE_WINDOW", lambda: closing_action(tk_titles, root))

为了防止这种情况

保持设置的持久性,以便在关闭应用程序时不会恢复默认设置。 在Python标准库中有一些存储数据的选项,如pickle、json、xml等等

对我来说,我将checkbutton的所有状态保存到一个元组中。比如:

settings = {sound: True, auto_complete: False,.....}

在关闭应用程序之前,应用程序会将元组写入一个文件(如setting.json)

json_string = json.dumps(settings)
with open(filepath, 'w') as fh:
    fh.write(json_string)

当我启动应用程序时,它将从文件中加载设置

with open(filepath, 'r') as fh:
    setting = json.loads(fh.read())

相关问题 更多 >

    热门问题