将持久值传递给类

And*_*ndy 0 python oop tkinter

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

我是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()
Run Code Online (Sandbox Code Playgroud)

mar*_*eau 5

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

这是一个更典型的方法来实现我认为你想要做的事情.它通过删除具有CheckButton由两者表示的状态的冗余来改变GUI,无论它是否被勾选以及显示为其标签的内容(即,如果它被检查,它是开启的).

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()
Run Code Online (Sandbox Code Playgroud)