简体   繁体   中英

How can I open an URL using PyQt when clicking on a button?

This my code which I want to open a http link, which is typed in URL field and link that to "OK" button so that I can open the link. I have a problem with this and cannot link the field area with the OK button. Please help.

def __init__(self):
    super(Example, self).__init__()

    self.initUI()
def initUI(self):

    b1 = QtGui.QPushButton("OK", self)
    b1.clicked.connect(open_webbrowser)
    b1.move(100,100)
    b2 =QtGui.QPushButton("EXIT", self)
    b2.clicked.connect(self.buttonClicked2)
    b2.move(300,100)


    l1 = QtGui.QLabel('URL',self)
    l1.move(100,20)
    self.add1 = QtGui.QLineEdit()


    l2 = QtGui.QLabel("PORT",self)
    l2.move(100,50)
    self.add2 = QtGui.QLineEdit()

    fbox = QtGui.QFormLayout()
    vbox = QtGui.QVBoxLayout() 

    vbox.addWidget(self.add1)
    vbox.addWidget(self.add2)
    fbox.addRow(l1,self.add1)
    fbox.addRow(l2,self.add2)   

    self.setLayout(fbox)
    self.setWindowTitle('URL STREAM')
    self.show()


def buttonClicked1(self):
    print self.add1.text()
    print self.add2.text()
    print "Streaming..."

def open_webbrowser(self):
    webbroser.open('http://www.google.com') 



def buttonClicked2(self):
    print "Exiting..."
    self.close()

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    ex.initUI()
    sys.exit(app.exec_())



if __name__ == '__main__':
    main()

You need to get the text from line edit eg:

def open_webbrowser(self):
    # if you want please remember to check its valid url or not
    url = str(self.add1.text())
    webbroser.open(url) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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