如何通过按钮命令(TkInter)使用os.startfile

发布于 2021-01-29 15:01:36

尝试在画布上实现按钮,该按钮在.pdf单击时会打开文件。

我的尝试如下

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)

不幸的是,我的代码.pdf在我单击按钮之前就打开了该文件,该文件已运行。为什么?

关注者
0
被浏览
89
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    当Python处理这两行时,它会在第一行看到这一点:

    os.startfile('Bessel.pdf')
    

    并将其解释为有效的函数调用。因此,它调用了该函数。

    要解决此问题,请定义一个函数来处理该行之前的click事件,然后将按钮的commandopion分配给该函数:

    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")
    

    或者,就像@JFSebastian指出的那样,您可以使用functools.partial

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

    请注意,您必须先导入functools



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看