【问题标题】:Passing persistent values into a class将持久值传递给类
【发布时间】:2015-06-02 06:44:42
【问题描述】:

在 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()

【问题讨论】:

  • 我认为,这是因为 Pin_ID,你在 _init_ 函数中有 Pin_ID 作为参数,但在 cbTest 中没有

标签: python oop tkinter


【解决方案1】:

如果您想记住构造函数参数的值,您需要使用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()

【讨论】:

    【解决方案2】:

    您想将PinID 保存在类实例变量中。这是在__init__ 中完成的

    self.PinID = PinID
    

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

    【讨论】:

    • 感谢 Tommy 的及时和有用的回答。我想知道为什么不能像在类 cbClass (Pin_ID) 中那样只在类定义中传递一个值,然后在类中全局使用该值?
    • 当你将它添加到self 时会发生这种情况,因为对象的实例数据和方法保存在self 中,并隐式传递给类的所有方法。您可能可以通过使用 global 关键字来实现全局定义,但这会很不自然,并且可能会对命名空间中的其他内容产生不利影响。 self 是在类中维护特定于实例的数据时要走的路
    【解决方案3】:

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

     self.Pin_ID = Pin_ID
    

    并通过使用 self. 在其他地方优先引用,如:

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

    我能够传递值。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多