I want to align the text of the button to the left with halign='left' in Kivy, but it does not work and keeps it centered.
This is my code:
import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.properties import StringProperty
from kivy.properties import ObjectProperty
class MyGrid(GridLayout):
def __init__(self, **kwargs):
super(MyGrid, self).__init__(**kwargs)
self.cols = 1
for i in range (0,10):
self.btn = Button(text=str(i),halign='left',background_color =(.3, .6, .7, 1))
self.btn.bind(on_press=self.pressed)
self.add_widget(self.btn)
def pressed(self, instance):
print ("Name:",instance.text)
class MyApp(App):
def build(self):
return MyGrid()
if __name__ == "__main__":
MyApp().run()
According to the documentation for halign:
This doesn’t change the position of the text texture of the Label
(centered), only the position of the text in this texture. You
probably want to bind the size of the Label to the texture_size or set
a text_size.
So, to get the result you want, you can define an extension to Button that does what the above documentation suggests:
class MyButt(Button):
pass
Builder.load_string('''
<MyButt>:
halign: 'left'
text_size: self.size
background_color: (.3, .6, .7, 1)
''')
Then use that class in your App:
class MyGrid(GridLayout):
def __init__(self, **kwargs):
super(MyGrid, self).__init__(**kwargs)
self.cols = 1
for i in range (0,10):
self.btn = MyButt(text=str(i))
self.btn.bind(on_press=self.pressed)
self.add_widget(self.btn)
Related
I'm a beginner at kivy, I have an fclass(Widget) that I want it to be a fclass(Screen), but when I tried to make the change all the screen messed up, the code generate some buttons with a for loop, I wish I coud do the same with a float layout, but I want the fclass to stay a screen since I'm building a multiscreen app.
Here is the .py file:
import kivy
from kivy.uix.gridlayout import GridLayout
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.widget import Widget
from kivy.uix.textinput import TextInput
from kivy.clock import Clock
from kivy.uix.image import Image
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.core.window import Window
from kivy.config import Config
from kivy.lang import Builder
from kivy.properties import StringProperty, ObjectProperty, NumericProperty,ReferenceListProperty
from kivy.graphics.texture import Texture
from kivy.core.camera import Camera
from kivy.graphics import *
import time
import os
from pathlib import Path
#import cv2
import struct
import threading
import pickle
Builder.load_file('the.kv')
class fscreen(Widget):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.list_of_btns = []
def create(self):
self.h = self.height*0.9
for i in range(4):
self.h = self.h - self.height*0.1
self.btn = Button(text='button '+str(i), size=(self.width*0.4,self.height*0.05), pos=(self.width*0.3, self.h), on_press=self.press)
self.list_of_btns.append(self.btn)
self.add_widget(self.btn)
def press(self, instance):
print(instance.text)
def delete(self):
for btns in self.list_of_btns:
self.remove_widget(btns)
class theapp(App):
def build(self):
self.screenm = ScreenManager()
self.fscreen = fscreen()
screen = Screen(name = "first screen")
screen.add_widget(self.fscreen)
self.screenm.add_widget(screen)
return self.screenm
if __name__ == "__main__":
theapp = theapp() #
theapp.run()
The .kv file:
<fscreen>
Button:
text: 'create'
size: root.width*0.4, root.height*0.05
pos: root.width*0.3, root.height*0.1
on_press: root.create()
Button:
text: 'delete'
size: root.width*0.4, root.height*0.05
pos: root.width*0.3, root.height*0.2
on_press: root.delete()
How can I make the fclass a screen class without messing up everything ?
Thank you in advance
Seems to me that code should work, but it doesn't. A fix is to use size_hint instead of size in both your kv and py. So the kv could look like:
<fscreen>:
Button:
text: 'create'
size_hint: 0.4, 0.05
# size: root.width*0.4, root.height*0.05
pos: root.width*0.3, root.height*0.1
on_press: root.create()
Button:
text: 'delete'
size_hint: 0.4, 0.05
# size: root.width*0.4, root.height*0.05
pos: root.width*0.3, root.height*0.2
on_press: root.delete()
and in the create() method:
def create(self):
self.h = self.height * 0.9
for i in range(4):
self.h = self.h - self.height * 0.1
self.btn = Button(text='button ' + str(i), size_hint=(0.4, 0.05),
pos=(self.width * 0.3, self.h), on_press=self.press)
self.list_of_btns.append(self.btn)
self.add_widget(self.btn)
Your size in the kv and py were both just trying to do the size_hint anyway.
And, of course, your build() method must be adjusted:
def build(self):
self.screenm = ScreenManager()
self.fscreen = fscreen(name="first screen")
self.screenm.add_widget(self.fscreen)
return self.screenm
Other things to note:
You should use upper case for class names. Failure to do so can lead to errors in kv
You should consider using pos_hint instead of pos to allow better resizing of your App
I've asked in past questions how to add and remove buttons dynamically.
I want to know how to dynamically delete BoxLayout with Python's Kivy.
Here is my code.
#-*- coding: utf-8 -*-
from kivy.config import Config
from kivy.uix.button import Button
Config.set('graphics', 'width', 300)
Config.set('graphics', 'height', 300)
Config.set('input', 'mouse', 'mouse,multitouch_on_demand') # eliminate annoying circle drawing on right click
from kivy.lang import Builder
Builder.load_string("""
<AddItemWidget>:
BoxLayout:
size: root.size
orientation: 'vertical'
RecycleView:
size_hint: 1.0,1.0
BoxLayout:
id: box
orientation: 'vertical'
Button:
id: addButton
text: "Add Item"
on_press: root.buttonClicked()
""")
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty
class RemovableButton(Button):
def on_touch_down(self, touch):
if touch.button == 'right':
if self.collide_point(touch.x, touch.y):
self.parent.remove_widget(self)
return True
return super(RemovableButton, self).on_touch_down(touch)
class AddItemWidget(Widget):
def __init__(self, **kwargs):
super(AddItemWidget, self).__init__(**kwargs)
self.count = 0
def buttonClicked(self):
self.count += 1
boxLayout = BoxLayout()
textinput = TextInput(text='Hello world'+str(self.count),size_hint_x=0.8)
deleteButton = RemovableButton(text='×',size_hint_x=0.2)
boxLayout.add_widget(deleteButton, index=1)
boxLayout.add_widget(textinput, index=1)
self.ids.box.add_widget(boxLayout, index=1)
deleteButton.bind(on_release=boxLayout.remove_widget)
class TestApp(App):
def __init__(self, **kwargs):
super(TestApp, self).__init__(**kwargs)
def build(self):
return AddItemWidget()
if __name__ == '__main__':
TestApp().run()
When the above code is executed, GUI will be launched and a line will be added by pressing the "Add Item" button.
I want to remove the line, so with the "x" button, as in the image below.
Its a little different than your other example.
For this, you need to use a different function to do the removing.
You also have to import partial like this: from functools import partial
And here is the changed AddItemWidget class:
class AddItemWidget(Widget):
def __init__(self, **kwargs):
super(AddItemWidget, self).__init__(**kwargs)
self.count = 0
def buttonClicked(self):
self.count += 1
boxLayout = BoxLayout()
textinput = TextInput(text='Hello world'+str(self.count),size_hint_x=0.8)
deleteButton = RemovableButton(text='×',size_hint_x=0.2)
boxLayout.add_widget(deleteButton, index=1)
boxLayout.add_widget(textinput, index=1)
self.ids.box.add_widget(boxLayout, index=1)
deleteButton.bind(on_release=partial(self.remove_btn, boxLayout)) # change this
def remove_btn(self, boxLayout, *args): # and add this
self.ids.box.remove_widget(boxLayout)
Can someone tell me how to show highlight switch widget when I set focus on Switch?It should be look like focused.
test.py
from kivy.uix.screenmanager import Screen
from kivy.app import App
from kivy.core.window import Window
from kivy.properties import StringProperty, ObjectProperty
from kivy.clock import Clock
Window.clearcolor = (0.5, 0.5, 0.5, 1)
Window.size = (200, 150)
class User(Screen):
swtch = ObjectProperty(None)
def __init__(self, **kwargs):
super(User, self).__init__(**kwargs)
Clock.schedule_once(self.swtch_focus, 1)
def swtch_focus(self, *args):
self.swtch.focus = True
class Test(App):
def build(self):
return self.root
if __name__ == '__main__':
Test().run()
test.kv
User:
swtch: swtch
BoxLayout:
orientation: "vertical"
GridLayout:
cols: 2
padding: 20, 20
spacing: 10, 10
Switch:
id:swtch
There is hoverableBehaviour in github here is the link https://gist.github.com/KeyWeeUsr/3166f13d363d5558f481d538c6a5d2aa copy the code and create a module to your current directory and import it to use it which you can add to your Widget to have the on focus or highlight feature. This is how to do.
class Highlight(HoverBehavior,Screen):
def on_enter(self):
print('Focus on')
def on_leave(self):
print('Focus off')
For some reason in kivy when you create a screen class and add a widget to it, specifically an image you get an image 10x bigger than the original for some reason compared to when you make a widget class and add that widget class as a child to the screen class. Here is my code for the kv file:
<StartScreen>
# Start Screen
name:'Start'
orientation: 'vertical'
FloatLayout:
id: Start_Layout
Image:
id: Start_Background
source: r'Images\Battle.jpg'
keep_ratio: True
allow_stretch: True
size: root.size
<MainScreen>
name: 'Main'
orientation: 'vertical'
FloatLayout:
Image:
source: r'Images\Button.png'
allow_stretch: True
keep_ratio: False
size: 100, 100
and for the python gui file...
from kivy.uix.widget import Widget
from kivy.uix.image import Image
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.animation import Animation
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.clock import Clock
from kivy.graphics.context_instructions import Color
from kivy.graphics.vertex_instructions import *
from kivy.core.window import Window
from kivy.app import App
from kivy.lang import Builder
import kivy
kivy.require('1.9.1')
VERSION = '1.9.1'
class GenericButton(Widget):
Builder.load_file('Button.kv')
def __init__(self, **kwargs):
super(GenericButton, self).__init__(**kwargs)
self.Button = self.ids['Button']
self.size = Window.size
def on_touch_down(self, touch):
self.Button.source = r'Images\ButtonPressed.png'
def on_touch_up(self, touch):
self.Button.source = r'Images\Button.png'
class wid(Widget):
def __init__(self, **kwargs):
super(wid, self).__init__(**kwargs)
self.Button = Image(source='Images\Animatio\glow.gif', allow_stretch=False, keep_ratio=True) (pretend its indented cus im new and it wouldn't let me add it to the code block)
self.add_widget(self.Button)
class StartScreen(Screen):
def __init__(self, **kwargs):
super(StartScreen, self).__init__(**kwargs)
#self.Layout = self.ids['Start_Layout']
#self.size = Window.size
#self.Layout.add_widget(GenericButton())
#self.ids['Start_Button'] = self.Layout.children[0]
print self.ids
#print self.ids.Start_Button.size
print self.size[0]/2, self.size[1]/2
class MainScreen(Screen):
def __init__(self, **kwargs):
super(MainScreen, self).__init__(**kwargs)
self.size = Window.size
def on_touch_down(self, touch):
self.Button.source = r'Images\ButtonPressed.png'
def on_touch_up(self, touch):
self.Button.source = r'Images\Button.png'
class ScreenManager(ScreenManager):
def __init__(self, **kwargs):
super(MCGMScreenManager, self).__init__(**kwargs)
Builder.load_file('Gui.kv')
self.add_widget(StartScreen())
self.add_widget(MainScreen())
And the app runs in the main file which i dont see a need to post. But an important thing might be that the app root class is ScreenManager
edit: i messed around a bit and i did this in python but i cleared the children of GenericButton and added the button that GenericButton used to own as a child of StartScreen and same result, a huge unresponsive image.
<MainScreen>
name: 'Main'
orientation: 'vertical'
FloatLayout:
Image:
source: r'Images\Button.png'
allow_stretch: True
keep_ratio: False
size: 100, 100
I didn't check if it's causing your particular issue, but the Image here doesn't take size 100, 100 because its parent (FloatLayout) is a layout class that automatically sets the size and position of its children. In this case, Image will automatically be resized to fill the FloatLayout.
To prevent this, add size_hint: None, None to the Image, to disable automatic resizing in both the horizontal and vertical directions. This generally applies whenever you add something to a Layout.
I want to show in a button and a label in a widget at left,center position and right,bottom without using .kv code . Here is my code and i am not able to figure out how to do it Can someone give advice ?
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.widget import Widget
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.button import Button
class Container(AnchorLayout):
def __init__(self, **kwargs):
super(Container, self).__init__(**kwargs)
btn = Button(text='Hello World',anchor_x='right',anchor_y='bottom')
self.add_widget(btn)
lbl = Label(text="Am i a Label ?",anchor_x='left',anchor_y='center')
self.add_widget(lbl)
class MyJB(App):
def build(self):
parent = Container()
return parent
if __name__ == '__main__':
MyJB().run()
The AnchorLayout aligns all widgets to a given point, not each widget to its own point. If you want widgets anchored in different locations, you need to use multiple AnchorLayouts. You also probably want to specify size and size_hint on either the AnchorLayout or the content widgets.
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.widget import Widget
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.button import Button
class Container(FloatLayout):
def __init__(self, **kwargs):
super(Container, self).__init__(**kwargs)
anchor_rb = AnchorLayout(anchor_x='right', anchor_y='bottom')
btn = Button(text='Hello World', size=(100, 100), size_hint=(None, None))
anchor_rb.add_widget(btn)
self.add_widget(anchor_rb)
anchor_lc = AnchorLayout(anchor_x='left', anchor_y='center')
lbl = Label(text="Am i a Label ?", size=(100, 100), size_hint=(None, None))
anchor_lc.add_widget(lbl)
self.add_widget(anchor_lc)
class MyJB(App):
def build(self):
parent = Container()
return parent
if __name__ == '__main__':
MyJB().run()
Personally, I find kv to be cleaner than manual widget creation, and it helps provide a definite separation between the UI and behavior.
kv version:
from kivy.app import App
from kivy.lang import Builder
root = Builder.load_string('''
FloatLayout:
AnchorLayout:
anchor_x: 'right'
anchor_y: 'bottom'
Button:
text: 'Hello World'
size: 100, 100
size_hint: None, None
AnchorLayout:
anchor_x: 'left'
anchor_y: 'center'
Label:
text: 'Am i a Label ?'
size: 100, 100
size_hint: None, None
''')
class MyJB(App):
def build(self):
return root
if __name__ == '__main__':
MyJB().run()