Reputation: 373
I am trying to write a basic text editor, which when the user uses the save menu bar, the function save will be called. I make a new frame and put in a Entry for user to enter name of file. I am adding a bind to the Entry so when the user presses the Enter key, it will call saveFile, which will eventually save the file correctly.
The issue is that it seems to be calling saveFile function when i am creating the bind, but unsure why it isn't waiting for me to press Enter key.
I have tried to find articles about it, but can't seem to find out issue.
def save(self):
tempWin = Tk()
frame = Frame(tempWin, width=100, height=100)
entry = Entry(frame)
frame.pack()
entry.pack()
entry.bind("<Return>",self.saveFile(entry,tempWin))
def saveFile(self,file,tempWin):
print("saveFile")
Upvotes: 0
Views: 74
Reputation:
Yes, that is exactly what is happening. When Python evaluates this line:
entry.bind("<Return>",self.saveFile(entry,tempWin))
it sees self.saveFile(entry,tempWin)
, which it interprets as a valid function call. So, it executes it.
You can fix the problem by "hiding" the call to self.saveFile
inside a lambda function:
entry.bind("<Return>", lambda e: self.saveFile(entry,tempWin))
Below is a simple script to demonstrate:
from tkinter import Tk
root = Tk()
root.bind("<Return>", lambda e: print('hi'))
root.mainloop()
The purpose of e
is to capture the click event that is sent to the function when the bind is triggered.
Upvotes: 2