How can I make a hyperlink in kivy? - python-2.7

How can I make a link that opens a web browser in Kivy? I've tried just putting the url in a label, but of course that doesn't work. I'd like it to work on the android app specifically and allow users to click it to open a web browser to that link.

Use webbrowser, it works already on Desktop, and our toolchain for iOS / Android have implemented a backend for it. Ie, use it, it will just works everywhere:
import webbrowser
webbrowser.open("http://kivy.org/")

You'll need to make the text clickable with the ref markup tag (see the markup documentation for details), and then bind it to a function that opens a web browser at the right page. On the desktop you could use the webbrowser module, on android you'll want to call android's normal functions with pyjnius. There's a prewritten example of how to do so here.
This is something that will probably go in the plyer project, which would provide a cross-platform way to open the right web browser on any supported system with a single python interface. It's not added yet though.

Now i make It perfact code for hyper link...you just need to use insance and function here is code :
#import necessary library
import webbrowser
def any_Function(instance):
webbrowser.open('http://www.anywebsite.domain')
class TutorialApp(App):
def build(self):
btn1 = Button(text='Open Link' , size=(200,50), size_hint=(None, None))
btn1.bind(on_press=any_Function)
#Bind function with button
return btn1
if __name__ == '__main__':
TutorialApp().run()

I know this is an old thread, but it took me quite a while to work this out so I figured that maybe someone else down the road might benefit. It's far from perfect but I made a hyperlink widget.
from kivy.uix.label import Label
import webbrowser
"""A kivy widget that implements a hyperlink"""
class Hyperlink(Label):
def __init__(self, **kwargs):
self.target = kwargs.pop('target')
kwargs['markup'] = True
kwargs['color'] = (0,0,1,1)
kwargs['text'] = "[u][ref=link]{}[/ref][/u]".format(kwargs['text'])
kwargs['on_ref_press'] = self.link
super().__init__(**kwargs)
def link(self, *args):
webbrowser.open(self.target)

#import necessary library
from tkinter import Button
import webbrowser
from kivy.uix.button import Button
from kivy.app import App
def any_Function(instance):
webbrowser.open('http://www.anywebsite.domain')
class TutorialApp(App):
def build(self):
btn1 = Button(text='Open Link' , size=(200,50), size_hint=(None, None))
btn1.bind(on_press=any_Function)
#Bind function with button
return btn1
if __name__ == '__main__':
TutorialApp().run()

Related

PyQt4 - can't get video to run with QMovie or Phonon

I'm having problems getting any video player to work with my PyQt4 setup (having tried both phonon and QMovie). The below QMovie script is from an example where several users commented it as functional. For me, it runs but only opens a window (with Loading... centered) that never actually plays the .gif (I've tried several working .gif files from numerous examples online, so the file is not the problem). I've commented out the results from running the three debugging steps as well.
What can I do next?
import sys
import os
import sip
sip.setapi('QVariant', 2)
from PyQt4 import QtGui, QtCore
class BusyLabel(QtGui.QWidget):
def __init__(self, gif, parent = None, text = None):
QtGui.QWidget.__init__(self, parent)
self.hlayout = QtGui.QHBoxLayout(self)
self.hlayout.setSpacing(0)
self.hlayout.setContentsMargins(0, 0, 0, 0)
self.setLayout(self.hlayout)
# Movie
self.movieLabel = QtGui.QLabel(self)
self.movieLabel.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
self.movieLabel.setAlignment(QtCore.Qt.AlignCenter)
self.movie = QtGui.QMovie(gif, QtCore.QByteArray(), self)
self.movie.setScaledSize(QtCore.QSize(20,20))
self.movie.setCacheMode(QtGui.QMovie.CacheAll)
self.movie.setSpeed(100)
print self.movie.isValid() #output = False
print self.movie.supportedFormats() #output = []
self.movieLabel.setMovie(self.movie)
self.hlayout.addWidget(self.movieLabel)
# Label
self.label = QtGui.QLabel(text)
self.hlayout.addWidget(self.label)
self.movie.start()
def setText(self, text):
self.label.setText(text)
def start(self):
self.show()
self.movie.start()
def stop(self):
self.hide()
self.movie.stop()
if __name__ == "__main__":
gif = 'test1.gif'
print os.path.exists(gif) #output = True
app = QtGui.QApplication(sys.argv)
player = BusyLabel(gif)
player.setText('Loading...')
player.start()
player.show()
sys.exit(app.exec_())
output:
True
False
[]
(For those curious about my other attempts, running a popular Phonon script gave the error: phonon backend plugin could not be loaded... I'll take anything at this point)
I'm providing here complete, working code that I've written to answer this (my) problem. All you need is PyQt4 and Matplotlib, I hope this might help someone else facing similar troubles down the road:
https://github.com/evanseitz/PyQt4_VideoPlayer

PyQt :Parent Window not waiting until child window closes.

PyQt :Parent Window not waiting until child window closes. with reference to code shared below ,My welcome class object should wait till first_time class object completely finishes executing , but instead goes ahead and closes it self before first_time object finishes executing .
code :
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PySide.QtCore import QSettings
import sys
from PyQt4 import uic
#importing first configuration class
import configure as config_first
#loading initial settings
settings=QSettings('settings.ini',QSettings.IniFormat)
#loading the ui screens
form_class=uic.loadUiType("screens/firstscreen.ui")[0]
class welcome(QDialog,form_class):
#this signal is emitted when first configuration is done and ready to go
done_and_go_to_use = pyqtSignal()
def __init__(self):
super(welcome, self).__init__()
self.setupUi(self)
self.done_and_go_to_use.connect(self.close)
self.ready_btn.clicked.connect(self.ready)
def ready(self):
if_configured = settings.value('isConfigured', False)
if not if_configured :
first_time=config_first.configureFirst(self)
first_time.show()
self.close()
app = QApplication(sys.argv)
p = welcome()
p.show()
app.exec_()
below is the code for configure.py
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sqlite3
import csv
from PySide.QtCore import QSettings
from PyQt4 import uic
#loading initial settings
settings=QSettings('settings.ini',QSettings.IniFormat)
#loading ui screens
form_class=uic.loadUiType("screens/config_first.ui")[0]
#database connecting
con = sqlite3.connect("local.db")
cur = con.cursor()
cur.execute("CREATE TABLE if not exists marks (student_id int,student_name varchar(200));")
class configureFirst(QDialog,form_class):
done_configuring=pyqtSignal()
try_again=pyqtSignal()
def __init__(self,parent=None):
super(configureFirst, self).__init__(parent)
self.setupUi(self)
self.ok_btn.clicked.connect(self.ok_clicked)
self.cancel_btn.clicked.connect(self.cancel_clicked)
self.try_again.connect(self.ok_clicked)
self.done_configuring.connect(self.cancel_clicked)
self.show()
def ok_clicked(self):
file_select=QFileDialog.getOpenFileName(self,"open file","/")
if file_select:
with open(file_select, 'rb') as f:
reader = csv.reader(f)
ed = list(reader)
for row in ed:
if "name" not in row or "id" not in row:
cur.execute("Insert into marks Values (?,?);",(row[0],row[1]))
con.commit()
settings.setValue("isConfigured",True)
self.done_configuring.emit()
else:
#if recurssion is used the no of time it has to close increases and leads to integration problems
self.try_again.emit()
def cancel_clicked(self):
if_configured=settings.value("isConfigured")
if if_configured:
self.close()
else:
QMessageBox.critical(self,"PerfAnalyser","You Need to Configure For PerfAnalyser To Work")
def closeEvent(self,event):
#this method is triggered when 'X' is clicked i.e close button is clicked at the upper right corner
if_configured = settings.value("isConfigured")
if if_configured:
event.accept()
else:
QMessageBox.critical(self, "PerfAnalyser", "You Need to Configure For PerfAnalyser To Work")
event.ignore()
Thanks for the help in advance ...
I will try to help out since I notice few people have seen your post. I have had this happen a long time ago so I need a reminder, but I was unable to get your code running, I also tried to recreate your ui files and the screens directory but I was not successful. However, maybe the following is still useful.
In my working code, any time I needed to create a subwindow, I executed subwindows as follows from the main window's module:
dlg = SubWindowModuleName.StartSub()
dlg.exec_()
This will execute the subwindow and waits for it to close. Then, on the subwindow module (SubWindowModuleName in the above code, "configure" for you), I did this:
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.resize(982, 521)
... # here I build the window (I noticed that you import UI files which is a much better way of doing this)
...
class StartSub(QtGui.QDialog, Ui_Dialog):
def __init__(self,parent=None):
QtGui.QDialog.__init__(self,parent)
self.setupUi(self)

How to add url to bookmark?

I am using PyQt4 for creating a custom browser using QtWebKit, but I am stuck on saving bookmarks from the browser. Does anyone know how to achieve that?
You're a little vague on how you want this done, so I'll say we wanted to use a button imported from a UI file called bookmarks_Btn. You'll need to use the pickle module.
Here's the example code...
from PyQt4 import QtCore, QtGui, QtWebKit, uic
import pickle
class window(QtGui.QWidget):
def __init__(self, parent=None):
super(httpWidget, self).__init__(parent)
self.ui = uic.loadUi('mybrowser.ui')
self.ui.setupUi(self)
def bookmarksLoad(self):
print 'Loading bookmarks'
try:
bookOpen = open('bookmarks.txt', 'rb')
bookmarks = pickle.load(bookOpen)
bookOpen.close()
print bookmarks # Not necessary, but for example purposes
# Here you decide how "bookmarks" variable is displayed.
except:
bookOpen = open('bookmarks.txt', 'wb')
bookmarks = 'http://www.stackoverflow.com'
bookWrite = pickle.dump(bookmarks, bookOpen)
bookOpen.close()
print bookmarks # Not necessary, but for example purposes
# Here you decide how "bookmarks" variable is displayed.
QtCore.QObject.connect(self.ui.bookmarks_Btn, QtCore.SIGNAL('clicked()'), self.bookmarksLoad)
self.ui.show()
def bookmarks():
url = input 'Enter a URL: '
bookOpen = open('bookmarks.txt', 'wb')
bookOpen.write(url)
bookOpen.close()
print 'Website bookmarked!'
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
run = window()
bookmarks()
sys.exit(app.exec_())
# You add on here, for example, deleting bookmarks.
However, if you wanted it to be retrieved from an address bar (named address, make the following changes...
# In the bookmarks function...
global url # Add at beginning
# Remove the input line.
# Add at end of __init__ in window class:
url = self.ui.address.text()
global url
That's pretty much the basics. Please note I normally program in Python 3 and PyQt5 so if there are any errors let me know :)

Aptana 3 Pydev not getting Tk() window after running

I am new to Aptana, and have searched the net to see how it handles gui development.
I have tried the following code. It shows no bugs in the console. However, it will not give me the Tk() window named myGui.
from Tkinter import *
import ttk
def main():
myGui = Tk()
myGui.title("My Gui New")
myGui.geometry('400x200+200+200')
l = Label(myGui, text="Help")
l.pack()
if __name__ == "__main__":
main()
Any pointers. I able to get my functions to run in the console, but this Gui development is not working out so well.
The-IT is right, you do want to add myGui.mainloop() to the end of main.
Normally when I'm working in Tkinter I try to move some of the information in your function main into the if... clause. This makes larger, more complex interfaces much easier to handle.
A good start is to use a class:
from Tkinter import *
from ttk import *
class App(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.pack()
self.create_widgets()
def create_widgets(self):
self.l = Label(self, text='Help')
self.l.pack()
if __name__ == '__main__':
root = Tk()
app = App(root)
root.mainloop()
The benefits of this is that you can easily introduce toplevels, add additonal widgets (in an organized fashion) and have clearer code. You can also use the classes to make templates for other widgets; in this case, you are building a special frame class and giving it whatever attributes you want. The same can be done for buttons, entries, and other frames. I'm not familiar with aptana3, but this should work with no problem. Just make sure your indentation is consistent.

How to integrate a Ipython console in a PyQT application

I am developing PyQt software for my lab. In this software, I am loading different kind of RAW and analyzed data from a mySQL database (usually in arrays).
I would like to integrate an Iython console in a Widget, so that I could interact easily with these data.
I had some difficulties with Ipython 0.13 to do this.
Here is what I already have (The whole code is very long, so I just show the part containing the widget, the Ipython console and the corresponding import line, if you need more, just tell me):
##I load everything useful to my application, including the following line
from IPython.frontend.qt.console.qtconsoleapp import IPythonQtConsoleApp
##then is my whole software
##here is a class containing the Graphical User Interface elements. A button call the following function. self.Shell_Widget is the widget containing the Ipython console, self.MainWindow is the application mainwindow
def EmbeddedIpython(self):
"""
This function should launch an Ipython console
"""
self.Shell_Widget = QtGui.QDockWidget(self.MainWindow) #Widget creation
self.MainWindow.addDockWidget(4,self.Shell_Widget)
self.Shell_Widget.setMinimumSize(400,420)
console = IPythonQtConsoleApp() #Console Creation
console.initialize()
console.start()
self.Shell_Widget.show()
So, as wanted, an Ipython console is launched, and seems to work, but I can not access the whole application variables ,arrays etc... I think the Ipython console is launched independently from my software, but here is my limit in programming...
Does someone know how to launch Ipython within my application? Maybe a missing parameter, or a different way to integrate Ipython.
for information, this doesn't work:
Embedding IPython Qt console in a PyQt application
Thank you for your help!!
The mentioned link seems to be working flawless here:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import atexit
from IPython.zmq.ipkernel import IPKernelApp
from IPython.lib.kernel import find_connection_file
from IPython.frontend.qt.kernelmanager import QtKernelManager
from IPython.frontend.qt.console.rich_ipython_widget import RichIPythonWidget
from IPython.utils.traitlets import TraitError
from PyQt4 import QtGui, QtCore
def event_loop(kernel):
kernel.timer = QtCore.QTimer()
kernel.timer.timeout.connect(kernel.do_one_iteration)
kernel.timer.start(1000*kernel._poll_interval)
def default_kernel_app():
app = IPKernelApp.instance()
app.initialize(['python', '--pylab=qt'])
app.kernel.eventloop = event_loop
return app
def default_manager(kernel):
connection_file = find_connection_file(kernel.connection_file)
manager = QtKernelManager(connection_file=connection_file)
manager.load_connection_file()
manager.start_channels()
atexit.register(manager.cleanup_connection_file)
return manager
def console_widget(manager):
try: # Ipython v0.13
widget = RichIPythonWidget(gui_completion='droplist')
except TraitError: # IPython v0.12
widget = RichIPythonWidget(gui_completion=True)
widget.kernel_manager = manager
return widget
def terminal_widget(**kwargs):
kernel_app = default_kernel_app()
manager = default_manager(kernel_app)
widget = console_widget(manager)
#update namespace
kernel_app.shell.user_ns.update(kwargs)
kernel_app.start()
return widget
class mainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(mainWindow, self).__init__(parent)
self.console = terminal_widget(testing=123)
print "\nAn Embeded Ipython Console!"
self.textEdit = QtGui.QTextEdit()
self.dockShell = QtGui.QDockWidget(self)
self.dockShell.setWidget(self.textEdit)
self.addDockWidget(4, self.dockShell)
self.setCentralWidget(self.console)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
main = mainWindow()
main.show()
sys.exit(app.exec_())