简体   繁体   中英

tkinter script to print entry text

I'm just starting to learn to use tkinter with python and it seems counterintuitive that this attempt at a simple script to print whatever is entered into the entry box, doesn't work:

class App:
    def __init__(self, master):

        frame  = Frame(master)
        frame.pack()

        text_write = Entry(frame)
        text_write.pack()

        self.button = Button(frame, text="quit", fg="red", command=frame.quit)
        self.button.pack(side=LEFT)

        self.hi_there = Button(frame, text='hello', fg='black', command=self.say_hi(text_write.get()))
        self.hi_there.pack(side=RIGHT)

    def say_hi(self, text):
        print(text)

root = Tk()

app = App(root)

root.mainloop()

This does nothing and outputs no errors, but if I change it to this:

class App:
    def __init__(self, master):

        frame  = Frame(master)
        frame.pack()

        self.text_write = Entry(frame)
        self.text_write.pack()

        self.button = Button(frame, text="quit", fg="red", command=frame.quit)
        self.button.pack(side=LEFT)

        self.hi_there = Button(frame, text='hello', fg='black', command=self.say_hi)
        self.hi_there.pack(side=RIGHT)

    def say_hi(self):
        print(self.text_write.get())

then it calls the function and prints the value. Why does the 'self' need to be declared there? And why can't you pass the value of text_write as an argument to say_hi (as in the first example) and have it display? Or can you and I'm just doing it wrong?

When you do this:

self.button = Button(..., command=func())

then python will call func() , and the result of that will be assigned to the command attribute. Since your func doesn't return anything, command will be None. That's why, when you push the button, nothing happens.

Your second version seems fine. The reason self is required is that without it, text_write is a local variable only visible to to the init function. By using self , it becomes an attribute of the object and thus accessible to all of the methods of the object.

If you want to learn how to pass arguments similar to your first attempt, search this site for uses of lambda and functools.partial . This sort of question has been asked and answered several times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM