【问题标题】:How to use os.startfile with a button command (TkInter)如何使用带有按钮命令的 os.startfile (TkInter)
【发布时间】:2013-12-13 00:14:43
【问题描述】:

尝试在画布上实现一个按钮,单击该按钮会打开一个.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 文件,它一运行就立即打开。为什么?

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    当 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

    【讨论】:

    • 第三个选项是functools.partial(os.startfile, "Bessel.pdf")
    猜你喜欢
    • 1970-01-01
    • 2013-04-19
    • 2019-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 2023-02-24
    相关资源
    最近更新 更多