TKInter 复选框变量始终为 0 [英] TKInter checkbox variable is always 0

查看:31
本文介绍了TKInter 复选框变量始终为 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 Python 的 TkInter 模块用于 GUI.下面是一个简单的复选框代码.

I'm using Python's TkInter module for a GUI. Below is a simple checkbox code.

def getCheckVal():
    print cbVar.get()

windowTime=Tk.Tk()
cbVar = Tk.IntVar()
btnC = Tk.Checkbutton(windowTime, text="Save", variable = cbVar, command=getCheckVal)
btnC.grid()
windowTime.mainloop()

此代码工作正常.每次我勾选复选框时,我得到 1,否则为 0.

This code works fine. Each time I tick the checkbox, I get 1, else 0.

但是,当我在从另一个 TkInter 命令(按下按钮时)调用的函数中运行相同的代码时,它停止工作.我总是得到 0 作为值.

However, when I run the same code in a function that is called from another TkInter command (when a button is pressed), it stops working. I always get 0 as the value.

class GUIMainClass:

    def __init__(self):
        '''Create the main window'''
        self.window = Tk.Tk()

    def askUser(self):
        def getCheckVal():
            print cbVar.get()

        windowTime=Tk.Tk()
        cbVar = Tk.IntVar()
        btnC = Tk.Checkbutton(windowTime, text="Save", variable = cbVar,
                              command=getCheckVal)
        btnC.grid()
        windowTime.mainloop()

    def cmdWindow(self):
        frameShow=Tk.Frame(self.window)
        frameShow.grid()
        btnSwitch = Tk.Button(frameShow, text='Show Plots', command=self.askUser)
        btnSwitch.grid()
        self.window.mainloop()

GUIObj=GUIMainClass()
GUIObj.cmdWindow()

这很不寻常.可能出什么问题了?

This is very unusual. What could be going wrong?

我使用了 2 个主循环,因为我想要一个单独的窗口 (windowTime) 在我单击显示绘图"按钮时打开.这个新窗口应该有复选框.

I've used 2 mainloops because I want a separate window (windowTime) to open up when I click "Show Plots" button. This new window should have the checkbox in it.

推荐答案

我不确定你要做什么,但一个问题是 TK.IntVar 调用了 askUser() 方法中创建的 >cbVar 将被删除,因此您需要将其附加到发生后仍然存在的内容.虽然您可以将其设为全局变量,但更好的选择是将其设为更持久且寿命"更长的属性.

I'm not sure what all you're trying to do, but one problem is that the TK.IntVar called cbVar that you create in your askUser() method will be deleted when the function returns, so you need to attach it to something that will still exist after that happens. While you could make it a global variable, a better choice would be to make it an attribute of something more persistent and has a longer "lifespan".

另一个可能的问题是,通常在单个 Tkinter 应用程序中应该只调用一次 mainloop().看起来您想要做的是显示通常称为 Dialog Window 的内容,Tkinter 也支持它.有一些内置的标准类,以及一些更通用的类来简化创建自定义类.这是我发现的一些文档,其中详细描述了它们.您可能还会发现查看他们的源代码很有帮助.在 Python 2 中,它位于 /Lib/lib-tk/tkSimpleDialog.py 文件和在 Python 3 中,代码位于名为 /Lib/tkinter/的文件中simpledialog.py.

Another likely issue is that generally there should only be one call to mainloop() in a single Tkinter application. It appears what you want to do is display what is commonly known as a Dialog Window, which Tkinter also supports. There's some standard ones built-in, plus some more generic classes to simplify creating custom ones. Here's some documentation I found which describes them in some detail. You may also find it helpful to look at their source code. In Python 2 it's in the /Lib/lib-tk/tkSimpleDialog.py file and in Python 3 the code's in a file named /Lib/tkinter/simpledialog.py.

下面的代码采用后一种方法,并从包含 Tkinter 库的通用对话框类派生一个名为 GUIButtonDialog 的自定义对话框类,该类简单地命名为 Dialog.

Below is code that takes the latter approach and derives a custom dialog class named GUIButtonDialog from the generic one included the Tkinter library which is simply named Dialog.

try:
    import Tkinter as Tk    # Python 2
    from tkSimpleDialog import Dialog
except ModuleNotFoundError:
    import tkinter as Tk    # Python 3
    from tkinter.simpledialog import Dialog


class GUIButtonDialog(Dialog):
    """Custom one Button dialog box."""
    def __init__(self, btnText, parent=None, title=None):
        self.btnText = btnText
        Dialog.__init__(self, parent, title)

    def getCheckVal(self):
        print(self.cbVar.get())

    def body(self, master):
        """Create dialog body."""
        self.cbVar = Tk.IntVar()
        self.btnC = Tk.Checkbutton(master, text=self.btnText, variable=self.cbVar,
                                   command=self.getCheckVal)
        self.btnC.grid()

        return self.btnC  # Return the widget to get inital focus.

    def buttonbox(self):
        # Overridden to suppress default "OK" and "Cancel" buttons.
        pass


class GUIMainClass:

    def __init__(self):
        """Create the main window."""
        self.window = Tk.Tk()

    def askUser(self):
        """Display custom dialog window (until user closes it)."""
        GUIButtonDialog("Save", parent=self.window)

    def cmdWindow(self):
        frameShow = Tk.Frame(self.window)
        frameShow.grid()
        btnSwitch = Tk.Button(frameShow, text='Show Plots', command=self.askUser)
        btnSwitch.grid()
        self.window.mainloop()


GUIObj = GUIMainClass()
GUIObj.cmdWindow()

这篇关于TKInter 复选框变量始终为 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆