我是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()))
即使按照图中的选择,我在控制台中也会看到以下内容: [0,0,0,0,0,0,0,0,0]
关于如何在tkinter窗口关闭后保持这些值,有什么想法吗?我在处理tkinter材料方面有哪些改进
编辑1:添加了可用于示例的标题列表。 编辑2:保留最少的代码示例
我找到了问题的解决办法。这是因为您没有为
IntVar
指定父级。只需更改即可
到
我注意到的另一个问题(我想这不是故意的)是,当窗口关闭时调用的函数在程序运行时立即被调用。要修复此问题,请将
title_window.protocol
行更改为为了防止这种情况
保持设置的持久性,以便在关闭应用程序时不会恢复默认设置。 在Python标准库中有一些存储数据的选项,如pickle、json、xml等等
对我来说,我将checkbutton的所有状态保存到一个元组中。比如:
在关闭应用程序之前,应用程序会将元组写入一个文件(如setting.json)
当我启动应用程序时,它将从文件中加载设置
相关问题 更多 >
编程相关推荐