Sarthak_Bisht
Sarthak_Bisht

Reputation: 27

how to acess the frame widgets from another function?

(my code is generating this error to_text.insert(END,'Click and Say...') NameError: name 'to_text' is not defined this prog is running fine if i am creating the frame after main window and then #calling only temp_fun() .but my code need to access frame widgets )

from tkinter import *
def frame1():
    f1=Frame(winchat).pack()    
    to_text=Text(f1).pack()
def temp_fun():
    to_text.insert(END,'Click and Say...')
winchat=Tk()
frame1()
temp_fun()

Upvotes: 1

Views: 921

Answers (2)

Mike - SMT
Mike - SMT

Reputation: 15236

It is probably better to create the frame and text box in the global name space. This way you can edit them from other functions. Keep in mind if you want to edit a widget later you will need use pack() on a separate line or else it will return None when you try to edit the widgets.

Take a look at the below example.

from tkinter import *


def temp_fun():
    global to_text # tell the function you want to edit this item in global
    to_text.insert(END,'Click and Say...')

winchat=Tk()

f1=Frame(winchat)
f1.pack()    
to_text=Text(f1)
to_text.pack()

temp_fun()

winchat.mainloop()

You do not need to add global in the function in this case because python will eventually check global as to_text is not defined in the function however I add the global here anyway for accuracy.

Upvotes: 1

diegoiva
diegoiva

Reputation: 484

You need to keep reference of to_text so you can access it on the other function, for that you can try using it as a global var.

from tkinter import *
to_text = None #<--- declaring it first.
def frame1():
    f1=Frame(winchat)
    f1.pack()   
    to_text=Text(f1)
    to_text.pack()
def temp_fun():
    to_text.insert(END,'Click and Say...')
winchat=Tk()
frame1()
temp_fun()

once you declare like that, you can reference it across any function.

Upvotes: 1

Related Questions