KIVY Text within label - label

Trying to place text within a Rectangle. I even tried solution given here.
I want the text to be within Rectangle. This should holds good even if I change window size please. When I add_widget Actor I still want to continue pos_hint and size_hint format. Any idea please..
from kivy.uix.label import Label
from kivy.uix.relativelayout import RelativeLayout
from kivy.properties import ListProperty
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.scatter import Scatter
from kivy.core.window import Window
Window.clearcolor = (1, 1, 1, 1)
Window.size = (800, 600)
kv = '''
<Actor>:
canvas:
PushMatrix
Color:
rgba: 0,1,0,.8
Rectangle:
id: _rect_
size: self.width, self.height/12
pos: 0, 11 * (self.height / 12)
Line:
points: self.width/2, 11 * self.height/12, self.width/2, 0
width:2
PopMatrix
Label:
id: _actr_lbl
text: 'Hello World'
markup: True
color: 0,0,0,1
pos: 0, 11 * self.height/12
halign: 'center'
'''
Builder.load_string(kv)
class Actor(Scatter):
def __init__(self, **kwargs) :
super(Actor, self).__init__(**kwargs)
class TestApp(App):
def build(self):
layout = RelativeLayout()
layout.add_widget(Actor(pos_hint = {'center_x':0.5, 'top':0.95}, size_hint = (0.2, 1)))
return layout
if __name__ == '__main__':
TestApp().run()

I think you can accomplish what you want by adjusting your kv for the Label slightly:
Label:
id: _actr_lbl
text: 'Hello World'
markup: True
color: 0,0,0,1
size_hint: None, None
size: root.width, root.height/12
pos: 0, 11 * root.height/12
halign: 'center'
Adding size_hint: None, None allows the size to be effective. And referencing root for size and pos info keeps the Label sized and positioned correctly.

Related

How do I generate an A4-sized single card in squib?

I'm trying to use Squib to generate a map for a boardgame by printing one "card" which is the size of an entire A4 sheet of paper.
There must be some default in Squib that is cropping the resulting images and text, however, so that only a portion of it is visible.
Here is some sample code demonstrating the problem:
require 'squib'
Squib::Deck.new cards: 1, layout: [] do
rect x: 0, y: 0, width: 3457, height: 2438, fill_color: 'BLUE'
circle x: 1728, y: 1218 , radius: 1218, fill_color: 'RED'
save_pdf file: 'maps_1.pdf'
end
At 300 dpi, a landscape A4 piece of paper should be 3457x2438 pixels, so this ought to display a blue box with a red circle, filling the page. Instead it displays a poker-card-sized chunk of that image in the upper left hand corner:
resulting pdf
The result is much the same if I use millimeters, with a sprue:
require 'squib'
Squib::Deck.new cards: 1, layout: [] do
rect x: 0, y: 0, width: '295mm', height: '208mm', fill_color: 'BLUE'
circle x: '147.5mm', y: '104mm' , radius: '104mm', fill_color: 'RED'
save_pdf file: 'maps_1.pdf', sprue: 'layouts/map-sprue.yml'
end
Sprue:
---
sheet_width: 297mm
sheet_height: 210mm
card_width: 295.0mm
card_height: 208.0mm
cards:
- x: 0.0mm
y: 0.0mm
crop_line:
lines:
- type: :vertical
position: 0.0mm
- type: :vertical
position: 295.0mm
- type: :horizontal
position: 0.0mm
- type: :horizontal
position: 208.0mm
Does anyone know what is forcing squib only to address a portion of the A4 page?
thanks
You want width and height as parameters to Squib::Deck.new
To make your "card" the entire size of an A4 page, use something like this:
Squib::Deck.new(width: '210mm', height: '297mm') do
end
HOWEVER If you are planning on printing to an A4 page I recommend making it a tad smaller so that your printer doesn't autoscale or cut things off. My printer does fine with 6mm margin, probably something like 200x290.
You probably don't need sprues in this situation.

How do you position a label in the center of screen in a scrollview within Kivy?

I'm having difficulty in positioning a label that has an image added using canvas within a scrollview. The desirable output is to have a label with text content as a paragraph followed by a label with an image and then followed by another label with text content as a paragraph.
The image is displaying in the correct position vertically as in its between the two text labels, but it is not positioning center when I attempt to scale down the image by multiplying the self.parent.width by .9 or whatever the decimal. It's binding it to the left screen and padding in the label is not working whereas it does work in the labels with text content. I have searched for documentation and other examples but could not find a solution to this. If anyone has experience with this or can provide any guidance, I'd greatly appreciate it. Please see my code below:
BoxLayout:
size_hint_y: .7
orientation: 'vertical'
canvas.before:
Color:
rgba: rgba('#FFFFFF')
Rectangle:
pos: self.pos
size: self.size
ScrollView:
id: sv
size_hint_y: None
height: self.parent.height
effect_cls: 'ScrollEffect'
GridLayout:
id: Content
cols: 1
size: self.minimum_size
size_hint: (1, None)
height: labelscroll1.texture_size[1]
Label:
id: labelscroll1
padding: ['20dp', '0dp']
color: rgba('#000000')
font_size: mtx.sp(14)
text_size: self.width, None
size: self.parent.width, self.texture_size[1]
size_hint: (None,None)
text: "Some text"
Label:
id: labelscroll2
padding: ['5dp','0dp']
size_hint: (None, None)
width: max(self.texture_size[0], self.parent.width)
height: 300
halign: 'center'
markup: True
canvas.before:
Rectangle:
pos: self.pos
size: self.size
source: 'Table.png'
Label:
id: labelscroll3
padding: ['20dp', '0dp']
color: rgba('#000000')
font_size: mtx.sp(14)
text_size: self.width, None
size: self.parent.width, self.texture_size[1]
size_hint: (None,None)
text: "Some text"
The indentations are four spaces in actual code but the formatting might be slightly off in here due to pasting.
Without seeing your actual code, I can only guess at what the problem actually is. But a good way to get something centered within a GridLayout cell is to use the AnchorLayout. Try replacing your middle Label in your kv with:
AnchorLayout:
size_hint: (1.0, None)
height: 300
Label:
id: labelscroll2
padding: ['5dp','0dp']
size_hint: (None, None)
width: max(self.texture_size[0], self.parent.width)
height: 300
halign: 'center'
markup: True
canvas.before:
Rectangle:
pos: self.pos
size: self.size
source: 'Table.png'

canvas.create_window not working?

I want to place a widget in my canvas.
I have written the following function to create a button and display it.
in the center of the x coordinate of my canvas.
def Button_Placer():
label1=Label(canvas, width =20, height = 2, font = font2, text="")
label1.pack()
def Show_Name():
name=NameGenerator()
label1.config(text=name)
button1=Button(canvas, text="Generate Name", width=20, height=4, font=font1, command=Show_Name)
button1=canvas.create_window(250, 300)
I have also created a canvas at the top:
canvas = Canvas(root, width=500, height = 500, bg="red")
canvas.pack()
Unfortunately the canvas.create_window does not work. .pack() works however is not what i need. I have looked at other examples however they are all off OOP and therefore do not find it relevant for my understanding.
As #CommonSense writes, try canvas.create_window(200, 200, window=button1).
Also; you create label1 inside a function and when the functioin exits the name label1 will be garbage collected.
When you create widgets on canvas the reference is an integer; the index of that widget on the canvas. If you use the widget name as reference for the canvas widget you lose the reference to the actual widget.
Try the example below:
from tkinter import *
root = Tk()
canvas = Canvas(root, width=500, height=500, bg="red")
canvas.pack()
def Show_Name():
name = 'A name' # No function NameGenerator()
label1.config(text=name)
button1 = Button(canvas, text="Generate Name", width=20, height=4,
command=Show_Name)
canvas_button1 = canvas.create_window(250, 300, window=button1)
label1 = Label(canvas, width=20, height=2, text="")
canvas_label1 = canvas.create_window(250, 200, window=label1)

Is there a max image size (pixel width and height) within wx where png images lose there transparency?

Initially, I loaded in 5 .png's with transparent backgrounds using wx.Image() and every single one kept its transparent background and looked the way I wanted it to on the canvas (it kept the background of the canvas). These png images were about (200,200) in size. I proceeded to load a png image with a transparent background that was about (900,500) in size onto the canvas and it made the transparency a black box around the image. Next, I opened the image up with gimp and exported the transparent image as a smaller size. Then when I loaded the image into python the image kept its transparency. Is there a max image size (pixel width and height) within wx where png images lose there transparency? Any info would help. Keep in mind that I can't resize the picture before it is loaded into wxpython. If I do that, it will have already lost its transparency.
import wx
import os
def opj(path):
return apply(os.path.join, tuple(path.split('/')))
def saveSnapShot(dcSource):
size = dcSource.Size
bmp= wx.EmptyBitmap(size.width, size.height)
memDC = wx.MemoryDC()
memDC.SelectObject(bmp)
memDC.Blit(0, 0, size.width, size.height, dcSource, 0,0)
memDC.SelectObject(wx.NullBitmap)
img = bmp.ConvertToImage()
img.SaveFile('path to new image created', wx.BITMAP_TYPE_JPEG)
def main():
app = wx.App(None)
testImage = wx.Image(opj('path to original image'), wx.BITMAP_TYPE_PNG).ConvertToBitmap()
draw_bmp = wx.EmptyBitmap(1500, 1500)
canvas_dc = wx.MemoryDC(draw_bmp)
background = wx.Colour(208, 11, 11)
canvas_dc.SetBackground(wx.Brush(background))
canvas_dc.Clear()
canvas_dc.DrawBitmap(testImage,0, 0)
saveSnapShot(canvas_dc)
if __name__ == '__main__':
main()
I don't know if I got this right. But if I convert your example from MemoryDC to PaintDC, then I could fix the transparency issue. The key was to pass True to useMask in DrawBitmap method. If I omit useMask parameter, it will default to False and no transparency will be used.
The documentation is here: http://www.wxpython.org/docs/api/wx.DC-class.html#DrawBitmap
I hope this what you wanted to do...
import wx
class myFrame(wx.Frame):
def __init__(self, testImage):
wx.Frame.__init__(self, None, size=testImage.Size)
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.testImage = testImage
self.Show()
def OnPaint(self, event):
dc = wx.PaintDC(self)
background = wx.Colour(255, 0, 0)
dc.SetBackground(wx.Brush(background))
dc.Clear()
#dc.DrawBitmap(self.testImage, 0, 0) # black background
dc.DrawBitmap(self.testImage, 0, 0, True) # transparency on, now red
def main():
app = wx.App(None)
testImage = wx.Image(r"path_to_image.png", wx.BITMAP_TYPE_PNG).ConvertToBitmap()
Frame = myFrame(testImage)
app.MainLoop()
if __name__ == '__main__':
main()
(Edit) Ok. I think your original example can be fixed in a similar way
memDC.Blit(0, 0, size.width, size.height, dcSource, 0,0, useMask=True)
canvas_dc.DrawBitmap(testImage,0, 0, useMask=True)
Just making sure that useMask is True was enough to fix the transparency issue in your example, too.

Must be string without null bytes, not str in pygame [duplicate]

This question already has answers here:
Animated sprite from few images
(4 answers)
How do I create animated sprites using Sprite Sheets in Pygame?
(1 answer)
Closed 2 years ago.
So I'm testing out this spritesheet code that I found on this site, and from another python file I wrote, I am trying to go and pass a spritesheet to it, where it will cut it up into a series of images, and allow to animate my monster in my game.
However, when I try to run it, I get this error:
python wormTest.py
Traceback (most recent call last):
File "wormTest.py", line 49, in <module>
worm = Worm()
File "wormTest.py", line 38, in __init__
img = pygame.image.load(outfile.getvalue())
TypeError: must be string without null bytes, not str
I was told to use CStringIO to help handle image input and output, but even after looking at the documentation, it is still a bit fuzzy to me. What is going on here?
The code I wrote for the worm:
import pygame
from sprite_sheet import sprite_sheet #handles sprite sheet stuff
import cStringIO #input output for images
# Define some colors
black = ( 0, 0, 0)
white = ( 255, 255, 255)
red = ( 255, 0, 0)
#initialize pygame
pygame.init()
#set the height and width of the screen
width = 800
height = 480
mainScreen = pygame.display.set_mode([width,height])
#A list of all of the sprites in the game
all_sprites_list = pygame.sprite.Group()
with open("big_worm.png", "rb") as infile:
outfile = cStringIO.StringIO()
outfile.write(infile.read())
class Worm(pygame.sprite.Sprite):
'''class that builds up the worm sprite'''
#constructor function
def __init__(self):
#call up the parent's constructor
pygame.sprite.Sprite.__init__(self)
images =[]
img = pygame.image.load(outfile.getvalue())
img.set_colorkey(white)#sets the color key. any pixel with same color as colorkey will be trasnparent
images = sprite_sheet(img, 40) #make up a sprite sheet
self.image = images[0]
self.rect = self.image.get_rect()
#creates a player object
worm = Worm()
#adds the player object to the all_sprites_list
all_sprites_list.add(worm)
#a conditional for the loop that keeps the game running until the user Xes out
done = False
#clock for the screen updates
clock = pygame.time.Clock()
#
# Game Logic Code
#
while done==False:
for event in pygame.event.get(): #user did something
if event.type == pygame.QUIT: #if the user hit the close button
done=True
mainScreen.fill(white)#makes the background white, and thus, the white part of the images will be invisible
#player.changeImage()
#limit the game to 20 fps
clock.tick(20)
#update the screen on the regular
pygame.display.flip()
pygame.quit()
And the code I'm using for the sprite_sheet:
#!/usr/bin/python
#
# Sprite Sheet Loader - hammythepig
#
# Edited by Peter Kennedy
#
# License - Attribution - hammythepig
#http://stackoverflow.com/questions/10560446/how-do-you-select-a-sprite-image-from-a-sprite-sheet-in-python
#
# Version = '2.0'
import pygame,sys
from pygame.locals import *
import cStringIO
def sprite_sheet(size,file,pos=(0,0)):
#Initial Values
len_sprt_x = size #sprite size
len_sprt_y = size
sprt_rect_x,sprt_rect_y = pos #where to find first sprite on sheet
sheet = pygame.image.load(file).convert_alpha() #Load the sheet
sheet_rect = sheet.get_rect()
sprites = []
print sheet_rect.height, sheet_rect.width
for i in range(0,sheet_rect.height-len_sprt_y,size[1]):#rows
print "row"
for i in range(0,sheet_rect.width-len_sprt_x,size[0]):#columns
print "column"
sheet.set_clip(pygame.Rect(sprt_rect_x, sprt_rect_y, len_sprt_x, len_sprt_y)) #find sprite you want
sprite = sheet.subsurface(sheet.get_clip()) #grab the sprite you want
sprites.append(sprite)
sprt_rect_x += len_sprt_x
sprt_rect_y += len_sprt_y
sprt_rect_x = 0
print sprites
return sprites
#VERSION HISTORY
#1.1 - turned code into useable function
#2.0 - fully functional sprite sheet loader

Resources