0

Trying to implement a button onto a canvas which opens a .pdf file when clicked.

My attempt is as follows

self.B3 = Button(InputFrame,text='Graphical Plots', command = os.startfile('Bessel.pdf'),bd=5,width=13,font="14")
self.B3.grid(column =0,row=3)

Unfortunately my code opens the .pdf file before I have clicked the button, as soon as it has run. Why?

Spamm
  • 3
  • 1
  • 3

1 Answers1

4

When Python processes those two lines, it sees this in the first:

os.startfile('Bessel.pdf')

and interprets it as a valid function call. So, it calls the function.

To fix the problem, define a function to handle the click event before that line and then assign the button's command opion to it:

def handler():
    # The code in here is "hidden"
    # It will only run when the function is called (the button is clicked)
    os.startfile('Bessel.pdf')
self.B3 = Button(InputFrame, text='Graphical Plots', command=handler, bd=5, width=13, font="14")

Or, even better/cleaner in this case, use a lambda (anonymous function):

self.B3 = Button(InputFrame, text='Graphical Plots', command=lambda: os.startfile('Bessel.pdf'), bd=5, width=13, font="14")

Or, as @J.F.Sebastian noted, you can use functools.partial:

self.B3 = Button(InputFrame, text='Graphical Plots', command=functools.partial(os.startfile, "Bessel.pdf"), bd=5, width=13, font="14")

Note that you will have to import functools first.