将持久值传递给类

时间:2015-03-29 05:51:19

标签: python oop tkinter

在Linux Mint中使用Python 2.7和Tkinter' Mate' 17环境

我对OOP完全陌生,并且不了解如何将持久值传递给类实例;在此代码中,"全局未定义"在第20行和第22行使用Pin_ID时生成错误:

 1  #!/usr/bin/env python
 2  import Tkinter as tk
 3
 4  root = tk.Tk()
 5
 6  class cbClass:
 7    def __init__(self, Pin_ID):
 8      self.cb_Txt=tk.StringVar()
 9      self.cb_Txt.set("Pin " + Pin_ID + " OFF")
10      self.cb_Var = tk.IntVar()
11      cb = tk.Checkbutton(
12        root,
13        textvariable=self.cb_Txt,
14        variable=self.cb_Var,
15        command=self.cbTest)
16      cb.pack()
17
18    def cbTest(self):
19      if self.cb_Var.get():
20        self.cb_Txt.set("Pin " + Pin_ID + " ON")
21      else:
22        self.cb_Txt.set("Pin " + Pin_ID + " OFF")
23
24  c1 = cbClass("8")
25  c2 = cbClass("E")
26  root.mainloop()

3 个答案:

答案 0 :(得分:5)

如果要记住构造函数参数的值,则需要使用self将其保存为类实例属性,如前所述。更基本的是,您需要改进的是GUI按钮设计以及Tkinter模块的相关用途。

这是一个更典型的方法来实现我认为你想要做的事情。它通过删除具有CheckButton状态的冗余来更改GUI,无论是否勾选显示为其标签的内容(即,如果已选中,则为ON)。

import Tkinter as tk

root = tk.Tk()

class cbClass:
    def __init__(self, PinID):
        self.PinID = "Pin " + PinID
        self.cbTxt = tk.StringVar()
        self.cbTxt.set(self.PinID)
        self.cb = tk.Checkbutton(root,
                                 text=self.PinID,
                                 variable=self.cbTxt,
                                 onvalue="ON", offvalue="OFF",
                                 command=self.cbTest)
        self.cb.pack()

    def cbTest(self):
        """ Called when checkbutton state is changed. """
        print("{} variable is now {}".format(self.PinID, self.cbTxt.get()))

c1 = cbClass("8")
c2 = cbClass("E")
root.mainloop()

答案 1 :(得分:3)

您想要保存PinID和类实例变量。这是__init__

self.PinID = PinID

并在cbTest中,您可以使用self.PinID访问,而不仅仅是PinID

答案 2 :(得分:0)

感谢Tommy:在-init - 中添加这一行:

 self.Pin_ID = Pin_ID

并在其他地方使用self引用引用,如:

 self.cb_Txt.set ("Pin " + self.Pin_ID + " ON")

我能够传递价值。

相关问题