如何在使用 PyQt5 时打开 python 中的文件
How do I open a file in python whilst using PyQt5
我希望使用 QPushButton 打开与程序位于同一文件夹中的文件。
这是我的代码:
file1 = self.lineedit1.text()
file1 = file1 + ".txt"
self.button1.clicked.connect(self.open_file(file1))
这是我调用的函数:
def open_file(clicked, file):
os.startfile(file)
知道为什么它不起作用吗?
非常感谢
编辑:当我 运行 它通过 IDLE (f5) 时,它甚至在构建 gui 之前就打开了文件,这意味着我什至还没有按下按钮,它正在调用函数,程序崩溃了.当我 运行 它通过单击可执行文件时它立即崩溃而没有打开文件并构建 gui。
Signal-Slot-Connections 必须在信号和 callable 之间建立。您立即调用 open_file-Function,而不是将其作为可调用的传递。
此外,您过早地评估 lineedit-text - 我假设您希望在单击按钮时获取它的值,而不是在代码 运行 设置时获取它的值。
因此代码大致如下所示:
# local function closure, thus it knows self
# from the surrounding
def open_file():
file1 = self.lineedit1.text() + ".txt"
os.startfile(file)
self.button1.clicked.connect(open_file) # no call!
我希望使用 QPushButton 打开与程序位于同一文件夹中的文件。 这是我的代码:
file1 = self.lineedit1.text()
file1 = file1 + ".txt"
self.button1.clicked.connect(self.open_file(file1))
这是我调用的函数:
def open_file(clicked, file):
os.startfile(file)
知道为什么它不起作用吗? 非常感谢
编辑:当我 运行 它通过 IDLE (f5) 时,它甚至在构建 gui 之前就打开了文件,这意味着我什至还没有按下按钮,它正在调用函数,程序崩溃了.当我 运行 它通过单击可执行文件时它立即崩溃而没有打开文件并构建 gui。
Signal-Slot-Connections 必须在信号和 callable 之间建立。您立即调用 open_file-Function,而不是将其作为可调用的传递。
此外,您过早地评估 lineedit-text - 我假设您希望在单击按钮时获取它的值,而不是在代码 运行 设置时获取它的值。
因此代码大致如下所示:
# local function closure, thus it knows self
# from the surrounding
def open_file():
file1 = self.lineedit1.text() + ".txt"
os.startfile(file)
self.button1.clicked.connect(open_file) # no call!