Kivy : Relative size of text displaying in a popup - python-2.7

Is there any way to make the message/title in the label fits into the popup ?
'message' or 'title' can be a long text that goes beyond the borders of the popup .
def popup_display(self, title, message):
btnclose = Button(text='Close me', size_hint_y=None, height=50)
content = BoxLayout(orientation='vertical')
content.add_widget(Label(text=message))
content.add_widget(btnclose)
popup = Popup(content=content, title=title,
size_hint=(None, None),
size=(300, 300),
auto_dismiss=False)
btnclose.bind(on_release=popup.dismiss)
popup.open()

Label has a text_size property, which allows to constraint its size to given bounding box. You can bind it to available size:
#!/usr/bin/python
# -*- coding: utf-8 -*-
from kivy.uix.popup import Popup
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.app import App
from kivy.lang import Builder
from functools import partial
class TestApp(App):
def build(self):
return Button(on_press=partial(self.popup_display, "title", "bar "*80))
def popup_display(self, title, message, widget):
btnclose = Button(text='Close me', size_hint_y=None, height=50)
l = Label(text=message)
l.bind(size=lambda s, w: s.setter('text_size')(s, w))
content = BoxLayout(orientation='vertical')
content.add_widget(l)
content.add_widget(btnclose)
popup = Popup(content=content, title=title, size_hint=(None, None), size=(300, 300), auto_dismiss=False)
btnclose.bind(on_release=popup.dismiss)
popup.open()
if __name__ == '__main__':
TestApp().run()
Text that won't fit will get removed. If you want to have it all you should use ScrollView inside of your popup.
As for title, it's not a Label but a string, so the best you can do is to add newlines:
return Button(on_press=partial(self.popup_display, "multiline\ntitle", "bar "*80))

Here'a a simpler version without BoxLayout and Button:
#!/usr/bin/python
# -*- coding: utf-8 -*-
from functools import partial
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.popup import Popup
class TestApp(App):
def build(self):
return Button(on_press=partial(self.popup_display, "title", "bar "*80))
def popup_display(self, title, message, widget):
l = Label(text=message)
l.bind(size=lambda s, w: s.setter('text_size')(s, w))
popup = Popup(content=l, title=title, size_hint=(None, None), size=(300, 200), auto_dismiss=True)
popup.open()
if __name__ == '__main__':
TestApp().run()
Simply click outside the popup to close it.

Related

Django: embedding image in template

I need an image to be displayed within my webpage. The image is stored within a variable in views.py.
Most solutions such as the one below use HttpResponse to output images but I want the image to be embedded within my html template.
from django.http import HttpResponse
def my_image(request):
image_data = open("/path/to/my/image.png", "rb").read()
PS. I am getting the image by using matplotlib to create the image. So I cannot use a static folder. Example code given below (credit:this)
import sys
from django.http import HttpResponse
import matplotlib as mpl
mpl.use('Agg') # Required to redirect locally
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import rand
try:
# Python 2
import cStringIO
except ImportError:
# Python 3
import io
def get_image(request):
"""
This is an example script from the Matplotlib website, just to show
a working sample >>>
"""
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = np.pi * (15 * np.random.rand(N))**2 # 0 to 15 point radiuses
plt.scatter(x, y, s=area, c=colors, alpha=0.5)
"""
Now the redirect into the cStringIO or BytesIO object >>>
"""
if cStringIO in sys.modules:
f = cStringIO.StringIO() # Python 2
else:
f = io.BytesIO() # Python 3
plt.savefig(f, format="png", facecolor=(0.95,0.95,0.95))
plt.clf()
"""
Add the contents of the StringIO or BytesIO object to the response, matching the
mime type with the plot format (in this case, PNG) and return >>>
"""
return HttpResponse(f.getvalue(), content_type="image/png")
return HttpResponse(image_data, content_type="image/png")
Save the image in the media directory and then use ajax to update the div
something like
def get_image(request):
"""
This is an example script from the Matplotlib website, just to show
a working sample >>>
"""
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = np.pi * (15 * np.random.rand(N))**2 # 0 to 15 point radiuses
plt.scatter(x, y, s=area, c=colors, alpha=0.5)
filepath = os.path.join(settings.MEDIA_PATH,'/name_of_the_file.png')
plt.savefig(filepath, facecolor=(0.95,0.95,0.95))
plt.clf()
return HttpResponse(filepath)
then go to the function with ajax request
$.ajax({ type: "POST",
url: 'THE URL TO THE FUNCTION',
data: {
csrfmiddlewaretoken: $('[name="csrfmiddlewaretoken"]').val(),
},
success: function(response){
$('#your_div_id').html("<img src=\""+responce+"\"></img>")
}
});

Update image on a label PyQT5

I am new in python. I want to update an image on label1. But function 'def browse' always give me blank label instead. Seems the code does not get the image or it failed to update the label, and the program did not give any error message. Did i missed something here? Also, print command below setPixmap command is executed. i am using python 2.7 and PyQT4.
Thanks in advance
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import os, sys
import cv2
from PIL.ImageQt import ImageQt
class GuiCakep(QtGui.QWidget):
global label1, label2
def __init__(self):
super(GuiCakep, self).__init__()
self.initUI()
def initUI(self):
self.setGeometry(100, 100, 1000, 600)
self.setWindowTitle('Single Browse')
self.label1 = QtGui.QLabel(self)
self.label1.setFrameShape(QtGui.QFrame.Box)
self.label1.setGeometry(QtCore.QRect(20, 10, 451, 451))
pixmap = QPixmap('1stimage.jpg')
self.label1.setPixmap(pixmap)
self.label2 =QtGui.QLabel(self)
self.label2.setFrameShape(QtGui.QFrame.Box)
self.label2.setGeometry(QtCore.QRect(481, 10, 451, 451))
btn = QtGui.QPushButton('Browse', self)
btn.resize(btn.sizeHint())
btn.clicked.connect(self.browse)
btn.move(775, 500)
self.show()
def browse(self):
filePath = QtGui.QFileDialog.getOpenFileName(self, 'a file','*.jpg')
fileHandle = open(filePath, 'r')
pixmap = QPixmap('filePath')
self.label1.setPixmap(pixmap)
print("Whoa awesome")
def main():
app = QtGui.QApplication(sys.argv)
w = GuiCakep()
app.exec_()
if __name__ == '__main__':
main()
You are creating a Pixmap with 'filePath' as argument. This is a string, not your variable filePath.
Remove the both ' and this should update the label.

Running a Kivy screen inside a Pyqt app ,

I am trying to make a simple maths quiz game that shows Numbers and when I press space it shows the result , the Application launch with a QTdyalog GUI first and after I finish configuring the gameplay a Kivy screen should show up and the game starts until the user press escape it gets back to the config GUI
here is the Programm skeleton
import kivy
from kivy.app import App
from kivy.uix.label import Label
import sys
from PyQt4 import QtCore, QtGui, uic
qtCreatorFile = "ConfigForm.ui" # Enter file here.
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)
class Playy(App): #the Kivy app
def build(self):
l = Label(text='Hello world')
return l
class Conf(QtGui.QDialog, Ui_MainWindow): #the COnfiguration Gui
def __init__(self):
QtGui.QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
self.setupUi(self)
self.buttonBox.accepted.connect(self.oky)
self.buttonBox.rejected.connect(self.notok)
def oky(self):
print "OK OK OK OK" #creating a Kivy app instance and running it
ins = Playy()
ins.run()
def notok(self):
print "cancel cancel"
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = Conf()
window.show()
sys.exit(app.exec_())
I am only having Issue with making functions inside the Kivy app class and passing arguments Into them and also handling Objects properties such as label text this is my first Kivy experiment tell me what do you think

How to make Scrollable label in kivy using .kv file

I am trying to make a scrollable label which has some text so here is my code
Here is my main.py
from kivy.app import App
import socket, sys, threading, os, time
class ExampleApp(App):
def build(self):
pass
if __name__ == "__main__":
ExampleApp().run()
Here is my example.kv file
ScrollView:
Label:
text:"hello world"*1000
I am facing issues with this....some one please post answer for this

How does one add a sub widget from a python file to a super widget defined in a kivy file?

I have a BoxLayout defined in a kivy file, and I am trying to add a label to this BoxLayout from a python file. Below are my python and kivy scripts. When I try to run the program as is, it fails, and I get an error message stating:
"properties.pyx", line 654, in kivy.properties.ObservableDict.__getattr__ (kivy\properties.c:9590)
KeyError: 'box'
How can I add a label (defined in dummy.py) to the BoxLayout (defined in dummy.kv) from dummy.py?
dummy.py shown below:
from kivy.app import App
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.lang import Builder
Builder.load_file('dummy.kv')
class test(BoxLayout):
box = ObjectProperty()
def __init__(self):
label = Label(text='Hello')
self.ids.box.add_widget(label)
class Test(App):
def build(self):
return test()
if __name__ == '__main__':
Test().run()
dummy.kv shown below:
#:kivy 1.8
<test>:
box: box
BoxLayout:
orientation: 'vertical'
id: box
You didn't initialize your test class properly:
from kivy.app import App
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.lang import Builder
Builder.load_file('dummy.kv')
class test(BoxLayout):
box = ObjectProperty()
def __init__(self):
label = Label(text='Hello')
super(test,self).__init__() #-------ADD THIS LINE
print(self.ids)
self.ids.box.add_widget(label)
class Test(App):
def build(self):
return test()
if __name__ == '__main__':
Test().run()
If those are really your filenames, the kv file is never loaded, so the BoxLayout with id 'box' does not exist. Rename the kv file to test.kv or use kivy.lang.Builder.load_file('dummy.kv').