如何将 os.startfile 与按钮命令一起使用 (TkInter) [英] How to use os.startfile with a button command (TkInter)
问题描述
试图在画布上实现一个按钮,点击时会打开一个 .pdf
文件.
Trying to implement a button onto a canvas which opens a .pdf
file when clicked.
我的尝试如下
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
文件,只要它运行.为什么?
Unfortunately my code opens the .pdf
file before I have clicked the button, as soon as it has run. Why?
推荐答案
当 Python 处理这两行时,它在第一行看到:
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.
要解决此问题,请定义一个函数来处理该行之前的点击事件,然后将按钮的 command
选项分配给它:
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")
<小时>
或者,在这种情况下甚至更好/更干净,使用 lambda
(匿名函数):
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")
<小时>
或者,正如@JFSebastian 所指出的,您可以使用 functools.partial
:
self.B3 = Button(InputFrame, text='Graphical Plots', command=functools.partial(os.startfile, "Bessel.pdf"), bd=5, width=13, font="14")
请注意,您必须先导入 functools
.
Note that you will have to import functools
first.
这篇关于如何将 os.startfile 与按钮命令一起使用 (TkInter)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!