访问 python 中 class 之外的 class 变量

Accessing class variables outside the class in python

我有一个 tkinter class。我想访问 class 之外的输入字段的值。我尝试通过创建一个函数来实现,但它打印的是地址而不是值。 这是我的代码

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 得到的输出是 <函数 first.get_id 在 0x0000016A7A41B430> 我也曾尝试将此值存储在全局变量中,但在 class 之外,它会给出 variable not deifned 错误 。 谁能帮我做这个?

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

下面是一个基于您的代码的简单示例

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

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