问题描述
为什么这个脚本一启动就打开文件?没有节目显示.
Why this script opens file as soon as it is launched? No program is showed.
按下按钮时应该打开文件.
It is supposed to open file when the button is pressed.
如果我删除 widget.connect
,则一切正常.但是按钮不起作用.
If I remove widget.connect
, then everything is ok. But the button does not working.
import sys
import os
from PyQt4 import QtGui, QtCore
# open file with os default program
def openFile(file):
if sys.platform == 'linux2':
subprocess.call(["xdg-open", file])
else:
os.startfile(file)
# pyQt
app = QtGui.QApplication(sys.argv)
widget = QtGui.QWidget()
button = QtGui.QPushButton('open', widget)
widget.connect(button, QtCore.SIGNAL('clicked()'), openFile('C:\file.txt'))
widget.show()
sys.exit(app.exec_())
这个 widget.connect
有什么问题?
推荐答案
在您的连接行中 openFile('C:\file.txt')
是对函数 openFile 的调用.当您将信号连接到插槽时,您应该传递一个可调用对象,例如一个函数,但您正在传递 openFile 的结果.
In your connect line openFile('C:\file.txt')
is a call to the function openFile. When you connect a signal to a slot you're supposed to pass a callable, e.g. a function but you're passing the result of openFile.
由于您想将参数硬编码到 openFile,您需要创建一个新函数,该函数不接受任何参数,并且在调用时调用 openFile('C:\file.txt')
.您可以使用 lambda 表达式执行此操作,因此您的连接线变为:
As you want to hard code the parameter to openFile you need to create a new function which takes no arguments and when called calls openFile('C:\file.txt')
. You can do this using a lambda expression, so your connect line becomes:
widget.connect(button, QtCore.SIGNAL('clicked()'), lambda: openFile('C:\file.txt'))
这篇关于PyQt 从一开始就跑槽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!