Question

I am learning somethings about Python Tkinter, and I wrote this simple code:

from Tkinter import * 
import tkMessageBox


def print_it(msg):
    Text1.insert(INSERT, str(msg))

top = Tk()




Entry1 = Entry(width=300)
Entry1.pack(side='top')
Button1 = Button(text='Send',width=300,command=print_it("Message"))
Button1.pack(side='top')

Text1 = Text(height=600,width=300)
Text1.pack(side='top')



top.geometry('640x480+10+10')
top.title('GUI')
top.mainloop()

I don't know why, but it is giving me the error:

NameError: global name 'Text1' is not defined

If I replace the Text1 in the print_it def with Entry1 , it won't give me any error.

Was it helpful?

Solution

You're calling print_it instead of using a reference to the function as the value of the command parameter.

Replace following line:

Button1 = Button(text='Send',width=300,command=print_it("Message"))

with

Button1 = Button(text='Send',width=300,command=lambda: print_it("Message"))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top