在python中访问类外的类变量

问题描述

我有一个 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 得到的输出 我还尝试将此值存储在全局变量中,但在类之外它会给出变量未定义错误。 有人可以帮我做这个吗?

解决方法

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

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

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,因为这是正常做法。