Python Forum
Calling widget from another function?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Calling widget from another function?
class Inv(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
		table_frame = tk.LabelFrame(main_frame, bg='yellow', width=640, height=720)
		tk_table = ttk.Treeview(table_frame, columns=imp_df.columns.values)
		t_entry = tk.Entry(self, width=100)
		table_frame.pack(side='right', fill='y', expand=True, anchor='e', ipadx=150)
		tk_table.pack(anchor='center', expand=True, fill='both')

		tk_table.bind("<<TreeviewSelect>>", self.insert_info)

	def insert_info(self, event):
		t_entry.insert(0, "test insert text")
I have tried numerous setups, but I cannot call my test entry widget (t_entry) from another function. I am wanting my entry widgets populated with the data that is selected on the tk tree, but when declaring a new function:
def insert_info(self, event):
		t_entry.insert(0, "test insert text")
"t_entry" is never recognized. I understand this code won't work, but I typed it to give an example of what I am trying to achieve.

Solved it unexpectedly.

def insert_info(self, event):
        t_entry.insert(0, "test insert text")
needed to be

def insert_info(self, event):
        self.t_entry.insert(0, "test insert text")
I also had to declare "self" on all my previous widgets to be able to call any widget appropriately.
Here's the explanation as to why you had to do that:

In your original code, t_entry was a local variable inside the __init__() method. Therefore, when the method finished, it ceased to exist. Whereas, when you name it self.t_entry, it becomes an attribute of the Inv class and exists after the __init__() method has finished. Then, to call it up again, you treat it like any other class attribute and call up Inv.t_entry - which is self.t_entry within the methods of the Inv class.

Possibly Related Threads…
Thread Author Replies Views Last Post
  Problem In calling a Function from another python file of project vinod2810 7 1,238 Oct-05-2019, 01:09 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020