简体   繁体   English

在使用PyQt5的同时如何在python中打开文件

[英]How do I open a file in python whilst using PyQt5

I wish to use a QPushButton to open a file that is contained in the same folder as the program. 我希望使用QPushButton打开与程序位于同一文件夹中的文件。 This is my code: 这是我的代码:

    file1 = self.lineedit1.text()
    file1 = file1 + ".txt"
    self.button1.clicked.connect(self.open_file(file1))

This is my function that is called: 这是我的函数,称为:

    def open_file(clicked, file):
        os.startfile(file)

Any idea why it isn't working? 知道为什么它不起作用吗? Many Thanks 非常感谢

EDIT: When I run it through IDLE (f5) it opens the file before it even builds the gui meaning I haven't even pressed the button yet and it is calling the function and the program crashes. 编辑:当我通过IDLE(f5)运行它时,它甚至在生成gui之前就打开了文件,这意味着我什至没有按下按钮,它正在调用该函数,并且程序崩溃。 When I run it by clicking the executable file it crashes instantly without opening the file and building the gui. 当我通过单击可执行文件运行它时,它立即崩溃,而没有打开文件并生成gui。

Signal-Slot-Connections must be made between a signal and a callable . Signal-Slot-Connections必须在signal和callable之间建立。 You invoke your open_file-Function immediately, instead of just passing it as callable. 您可以立即调用open_file-Function,而不仅仅是将其传递为可调用的。

Also, you evaluate the lineedit-text too early - I presume you want to take it's value when the button is clicked, not when the code is run to set things up. 另外,您对lineedit文本的评估还为时过早-我想您想在单击按钮时获取它的价值,而不是在运行代码进行设置时获取它的价值。

Thus the code looks roughly like this: 因此,代码大致如下所示:

 # 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!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM