Chris Bao
Chris Bao

Reputation: 2868

Python: how to access a widget of the pop up window

In my Python GUI script, I have a pop up window, and there is text area widget on the pop-up window, users can input some content inside, and then click one button on the pop-up window to get the input text.
But it seems that in the defined function, the widget on the pop-up window can not be accessed. the code goes as following:

from Tkinter import *

def Add_Content():
    content = ent_new.get("1.0","end")
    print content

def Add_Task():
    task_index = 1
    new_window = Toplevel()
    label1 = Label(new_window, text="New Goal:")
    label1.grid(row = 0, column = 0)
    ent_new = Text(new_window, bg= "white", height=5, width= 30)
    ent_new.grid(row=0,column =1,padx=5, pady=5)
    bu_new = Button( new_window,text="Add", command = Add_Content)
    bu_new.grid(row=0, column =2)
    new_window.focus_force()


master = Tk()
group = LabelFrame(master, text="Operation", padx=5, pady=5, relief = RAISED)
group.grid(row=0,column= 0, padx=10, pady=10, sticky=N)
bu_add = Button(group, text = "Add Task",width = 15, command = Add_Task)
bu_add.grid(row=0,column=0)
mainloop()

in the above script, the ent_new can not be found in function Add_Content

Upvotes: 0

Views: 440

Answers (2)

Rolf of Saxony
Rolf of Saxony

Reputation: 22443

Without adding a class and the concept of self and parent, you can use lambda given in the first answer or you can use a global variable.
Note: In python circles globals are rather frowned upon but they work and get the job done.

from Tkinter import *
global ent_new

def Add_Content():
    content = ent_new.get("1.0","end")
    print content

def Add_Task():
    global ent_new
    task_index = 1
    new_window = Toplevel()
    label1 = Label(new_window, text="New Goal:")
    label1.grid(row = 0, column = 0)
    ent_new = Text(new_window, bg= "white", height=5, width= 30)
    ent_new.grid(row=0,column =1,padx=5, pady=5)
    bu_new = Button( new_window,text="Add", command = Add_Content)
    bu_new.grid(row=0, column =2)
    new_window.focus_force()


master = Tk()
group = LabelFrame(master, text="Operation", padx=5, pady=5, relief = RAISED)
group.grid(row=0,column= 0, padx=10, pady=10, sticky=N)
bu_add = Button(group, text = "Add Task",width = 15, command = Add_Task)
bu_add.grid(row=0,column=0)
mainloop()

Upvotes: 1

Ilya Peterov
Ilya Peterov

Reputation: 2065

The problem is that ent_new is in another namespace. You can solve it by making Add_Content recieve ent_new in the arguments like that,

def Add_Content(my_ent):
    content = my_ent.get("1.0","end")
    print content

and then using a wrapper function (lambda) when passing it to Button

bu_new = Button( new_window,text="Add", command = lambda: Add_Content(ent_new))

Upvotes: 1

Related Questions