I have a tkinter class. I want to access the value of entry field outside the class. I have tried doing it by creating a function but it is printing the address and not the value. Here is my code
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)
the output i am getting by calling first.get_id
is
<function first.get_id at 0x0000016A7A41B430>
I have also tried to store this value in a global variable but outside class it gives variable not deifned error.
Can anyone help me doing this?
First you need to create an instance of the class, then you can use that instance to access its instance variable and function.
Below is a simple example based on your code
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()
Note that I have change class name from first
to First
because it is normal practise.