当 Python 处理这两行时,它会在第一行看到:
os.startfile('Bessel.pdf')
并将其解释为有效的函数调用。所以,它调用了这个函数。
要解决此问题,请在该行之前定义一个处理点击事件的函数,然后将按钮的command 选项分配给它:
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")
或者,在这种情况下更好/更干净,使用lambda(匿名函数):
self.B3 = Button(InputFrame, text='Graphical Plots', command=lambda: os.startfile('Bessel.pdf'), bd=5, width=13, font="14")
或者,正如@J.F.Sebastian 所说,您可以使用functools.partial:
self.B3 = Button(InputFrame, text='Graphical Plots', command=functools.partial(os.startfile, "Bessel.pdf"), bd=5, width=13, font="14")
请注意,您必须先导入 functools。