E.SAYB
E.SAYB

Reputation: 31

Tkinter: How to assign two commands to a button via a function?

I am wanting to make an 'Enter Name' entry that prints a welcome message to the user. I recently posted asking for help on how to switch frames in tkinter. I figured it out and solved that problem.

However, now I want to switch frames and print an entry to a label when hitting a button. I don't receive any errors in my code however the returnEntry() function doesn't do anything. It doesn't raise the frame and I don't think it retrieves the entry text either.(without the returnEntry() function the frame does raise the frame, but with the code it doesn't. Does that make sense or am I complicating things?

Here is the code:

def show_frame(frame):
    frame.tkraise()


def returnEntry():
    result=NameEntry.get()
    Label3.config(text=result)

def WelcomeName():
    show_frame(f3)
    returnEntry()


f1 = Frame(root)
f2 = Frame(root)
f3 = Frame(root)
f4 = Frame(root)
for frame in (f1, f2, f3, f4):
    frame.config(width=500,height=500, bg="light blue")
    frame.place(relx=0.5,rely=0.5,anchor="center")


#First Page
Button(f1, text='Click to Play', command=lambda: show_frame(f2)).place(relx=0.5,rely=0.5,anchor="center")
Label(f1, text='Magic 8 Ball', fg="White", bg="dark blue",
      font="Veranda 19").place(relx=0.5,rely=0.20,anchor="center")


#Second page
Label(f2, text='Enter your name:',fg="White", bg="dark blue",
      font="veranda 17").place(relx=0.5,rely=0.40,anchor="center")
NameEntry=Entry(f2,font="veranda 15").place(relx=0.5,rely=0.5,anchor="center")
Button2=Button(f2, text='Continue', font="veranda 15",
       command=lambda: returnEntry).place(relx=0.5,rely=0.60,anchor="center")


#Third Page
Label3=Label(f3,text="",bg="light blue",font="veranda 15").place(relx=0.5,rely=0.35,anchor="center")
Label4=Label(f3, text="Ask me a yes or no question and reveal the truth" , bg="light blue",font="veranda 15")
Label4.place(relx=0.5,rely=0.45,anchor="center")
QuestionEntry=Entry(f3, font="veranda 15").place(relx=0.5,rely=0.52,anchor="center")
Button(f3, text='Ask away', command=lambda: show_frame(f4)).place(relx=0.5,rely=0.6,anchor="center")

Sorry for sloppy code etc...

Upvotes: 1

Views: 663

Answers (1)

Novel
Novel

Reputation: 13729

You can't. You will have to make a 3rd function that calls the two you want, and give that 3rd function to the Button command.

def on_click():
    do_thing_1()
    do_thing_2()

btn = Button(command=on_click)

I highly recommend you stay away from lambda until you know how it works.

Also, you shouldn't initialize and layout widgets on the same line, it leads to bugs. Always use 2 lines.

# BAD: NameEntry is None, and can't be used
NameEntry=Entry(f2,font="veranda 15").place(relx=0.5,rely=0.5,anchor="center")

# good: NameEntry is an Entry instance, and can be used later
NameEntry=Entry(f2,font="veranda 15")
NameEntry.place(relx=0.5,rely=0.5,anchor="center")

Upvotes: 2

Related Questions