Checkbutton不会设置为可变值

时间:2019-05-28 15:53:41

标签: python tkinter python-2.x

我创建了一个简单的Python Tkinter gui,我无法用正确的值来使Checkbutton初始化,无论我做什么,都始终未选中它们,而代码中的两个打印则显示出来:

('dryRunVar', 0)
('useGenreSubFolderVar', 1)

我也尝试过使用BooleanVar的所有方法,但无法使其工作

如果将CheckButton()的实例化为ttk.CheckButton(),这很奇怪,那么两个按钮都处于“灰色”状态

即使将对配置值的调用更改为常量0和1也不会更改任何内容,按钮保持未选中状态

也尝试围绕Tk实例化和mainloop进行一些调整,但没有成功

#!/usr/lib/python2.7/
# -*- coding: utf-8 -*-

from Tkinter import *
import conf,ttk

class GUI():

    def __init__(self,window, configuration) :
        self.configuration = configuration
        self.window = window
        self.draw()

    def draw(self) :
        self.root = Frame(self.window,padx=15,pady=15,width=800,height=200)
        self.root.grid(column=0,row=0)        
        self.drawParametersFrame()

    def drawParametersFrame(self) :
        #Parameters frame
        self.parametersFrame = LabelFrame(self.root,text="Sorting Parameters",padx=15,pady=15)
        self.parametersFrame.grid(column=0,row=2,sticky="EW")
        dryRunVar = IntVar()
        dryRunVar.set(self.configuration['dryRun'])
        print("dryRunVar",dryRunVar.get())
        dryRunCheckButton = Checkbutton(self.parametersFrame,text="Dry Run", variable=dryRunVar, onvalue=1, offvalue = 0)
        dryRunCheckButton.grid(column=0,row=0,sticky="W")
        useGenreSubFolderVar = IntVar()
        useGenreSubFolderVar.set(self.configuration['genreSubFolders'])
        print("useGenreSubFolderVar",useGenreSubFolderVar.get())
        useGenreSubFolderCheckButton = Checkbutton(self.parametersFrame,text="Use genre subfolders", variable=useGenreSubFolderVar, onvalue=1, offvalue = 0)
        useGenreSubFolderCheckButton.grid(column=2,row=0,sticky="W")

if __name__ == "__main__":
    configuration = conf.loadConf(r"/home/thomas/code/perso/python/conf.conf")
    window = Tk()
    gui = GUI(window,configuration)
    window.mainloop()

1 个答案:

答案 0 :(得分:2)

改为将IntVar设为类的属性。

def drawParametersFrame(self) :
    ...
    self.dryRunVar = IntVar()
    self.dryRunVar.set(1)
    dryRunCheckButton = Checkbutton(self.parametersFrame,text="Dry Run", variable=self.dryRunVar, onvalue=1, offvalue = 0)
    ...
    self.useGenreSubFolderVar = IntVar()
    self.useGenreSubFolderVar.set(1)
    useGenreSubFolderCheckButton = Checkbutton(self.parametersFrame,text="Use genre subfolders", variable=self.useGenreSubFolderVar, onvalue=1, offvalue = 0)
    ...