Search code examples
pythonpython-3.xtkinterruntime-error

Tkinter askopendialog runtime error after dialog confirmation


Consider the following code snippet:

from tkinter import *
import tkinter.filedialog as fd

def mycallback(event):
    fname = fd.askopenfilename()
    print(fname)   

root = Tk()
b1 = Button(root, text='Hello!')
b1.bind('<Button-1>', mycallback)
b1.pack()
root.mainloop()

After pressing the button b1 an open-dialog appears as supposed. If I press OK or CANCEL after choosing a file, the program crashes with exit code 139.

What's the problem here?

I'm using Python 3.4 on OS X 10.6.8.


Solution

  • Calling a function when clicking a button can be done using the button's callback argument. So instead of binding <Button-1> to the button you should use

    b1 = Button(root, text='Hello!', command=mycallback)
    

    You should then also remove the event argument from the mycallback function, since command doesn't pass any arguments.

    How this solves your problem, I really dont know. But according to your comment it does.

    For more information on the Button (and any other) widget, see effbot.org