【问题标题】:Accessing class variables outside the class in python在python中访问类之外的类变量
【发布时间】:2021-07-23 17:50:26
【问题描述】:

我有一个 tkinter 课程。我想访问类外输入字段的值。我尝试通过创建一个函数来做到这一点,但它打印的是地址而不是值。 这是我的代码

class first:
    def __init__(self, root):
        self.root = root
        self.root.title('First window')
        self.root.geometry('1350x700+0+0')
        
        self.mystring = tkinter.StringVar(self.root)


        self.txt_id = Entry(self.root, textvariable=self.mystring, font=("Times New Roman", 14), bg='white')
        self.txt_id.place(x=200, y=400, width=280)

    btn_search = Button(self.root, command=self.get_id)
        btn_search.place(x=100, y=150, width=220, height=35)

     def get_id(self):
        print(self.mystring.get())
        return self.mystring.get()
     print(get_id)
print(first.get_id)

我通过调用first.get_id 得到的输出是 我也尝试将此值存储在全局变量中,但在类之外它给出了variable not deifned error。 谁能帮我做这个?

【问题讨论】:

  • 我们无法运行您的代码,这不是一个最小的完整示例。
  • 您需要创建类的实例才能访问其实例变量或函数,但它们是类变量和函数。
  • 你没有打电话 first.get_id,你正在查找它。即使这样,您也必须/应该调用实例上的方法,而不是类。
  • 你的意思是@MisterMiyagi value = first id_value=value.get_id print(id_value)。它正在打印同样的东西。
  • @acw1668 你能告诉我怎么做吗?我正在这样做,但没有得到想要的价值。

标签: python tkinter methods class-method python-class


【解决方案1】:

首先你需要创建一个类的实例,然后你可以使用这个实例来访问它的实例变量和函数。

以下是基于您的代码的简单示例

import tkinter as tk

class First:
    def __init__(self, root):
        self.root = root
        self.root.title('First window')
        self.root.geometry('1350x700+0+0')
        
        self.mystring = tk.StringVar(self.root)

        self.txt_id = tk.Entry(self.root, textvariable=self.mystring, font=("Times New Roman", 14), bg='white')
        self.txt_id.place(x=200, y=400, width=280)

        btn_search = tk.Button(self.root, text="Show in class", command=self.get_id)
        btn_search.place(x=100, y=150, width=220, height=35)

    def get_id(self):
        val = self.mystring.get()
        print("inside class:", val)
        return val

root = tk.Tk()

# create an instance of First class
app = First(root)

def show():
    # get the text from the Entry widget
    print("outside class:", app.get_id())

tk.Button(root, text="Show outside class", command=show).pack()

root.mainloop()

请注意,我已将班级名称从 first 更改为 First,因为这是正常做法。

【讨论】:

  • 我会尝试这种方式。我想我没有搞清楚。
猜你喜欢
  • 1970-01-01
  • 2019-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-16
  • 1970-01-01
  • 1970-01-01
  • 2013-05-11
相关资源
最近更新 更多