Add custom widgets at runtime to screens - python-3.x

I want to add Buttons (Basicly custom Buttons with Image) as a custom Widgets to "Screen1" but I always end up with "_event.pyx not found" Error.
I've tried with "super().init(**kwargs)" and without.
Python code:
sm = ScreenManager()
class DrinkWidget(Widget):
pass
class HomeScreen(BoxLayout):
def switch(self, to):
#Swithing funktion
#This is the Part, that causes the Problem I think:
class Screen1(Screen):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.add_widget(DrinkWidget(
lable_text_optn = 'test'
))
class Screen2(Screen):
pass
class ZapfanlageApp(App):
icon = 'GUI_Elemente/app_icon.png'
title = 'Zapfanlage'
def build(self):
pass
if __name__ == "__main__":
ZapfanlageApp().run()
Kivy code (separate .kv File. The part "HomeScreen" works so far):
HomeScreen:
sm: sm
name: 'ScreenManager'
BoxLayout:
orientation: 'vertical'
rows: 2
ActionBar:
pos_hint: {'top': 1}
size_hint_y: .065
ActionView:
ActionButton:
text: 'Cocktails'
on_press:
root.switch(1)
ActionButton:
text: 'Drinks'
on_press:
root.switch(2)
ActionButton:
text: 'Einstellungen'
on_press:
root.switch(3)
ScreenManager:
id: sm
size_hint_y: .935
Screen1:
name: "screen1"
id: screen1
Screen2:
name: "screen2"
id: screen2
<Screen1#Screen>:
name: "screen_1"
id: screen1
#Here should the Buttons in GridLayout appear
<Screen2#Screen>:
name: "screen_2"
id: screen2
#This is the Custom Button I want to be inserted above
<Drink_Widget#Button>:
image_path_optn: image_path
lable_text_optn: lable_text
Button:
size_hint_x: None
size_hint_y: None
height: (root.height) -10
width: 250
on_press:
BoxLayout:
orientation: "vertical"
width: root.width
height: root.height
pos_hint: root.pos
pos: root.pos
padding: 5
Image:
source: image_path
Label:
text: label_text
I want to show a various number of DrinkWidgets on screen1 vertically and add them in runtime. But I always end up with nothing showing up or with _event.pyx not found error. Passing the code under <Screen1#Screen>: directly works.
I hope someone can help me. Thanks a lot!

Okay, it looks like you want to add a number of your DrinkWidgets to your screen when your app loads. First things first, in your .py file you have defined a class named Drink_widget but in .kv you call it DrinkWidget
Next, since you have your DrinkWidget defined as inheriting the Button class from kivy, you can easily change the text in the DrinkWidget using the text: field. Similarly, you can change the image that the button displays to be whatever you like using the background_normal: field. To change the image displayed when you click the button, use the background_down: field. Example:
<DrinkWidget#Button>:
text: "some text"
background_normal: "image1.png"
background_down: "image2.png"
So you don't need your lable_text_optn or image_path_optn fields.
Also, you are trying to add a number of widgets to a Screen widget, when really you should be adding a number of widgets to a Layout widget (FloatLayout, BoxLayout, or GridLayout). Your Screen widget should only have the Layout widget as its direct child.
Another issue I see is you have two root widgets inside your .kv file -- HomeScreen and BoxLayout unless your indentation is correct in the question.
Here is a minimal example of what I believe you are trying to get working:
main.py
from kivy.app import App
from kivy.uix.button import Button
class DrinkWidget(Button):
pass
class MainApp(App):
def on_start(self):
# This command is automatically called when your app loads up
the_screen_grid = self.root.ids.some_descriptive_id
# self.root refers to the root widget, which is the GridLayout
# self.root.ids gets me a DictProperty of all children widgets that have an id associated with them
# self.root.ids.some_descriptive_id gets me the GridLayout widget I defined with the id: some_descriptive_id
for i in range(3):
the_screen_grid.add_widget(DrinkWidget(text="drink " + str(i)))
MainApp().run()
main.kv
GridLayout:
cols: 1
Screen:
# Widgets that aren't Layouts normally only have 1 child widget
# To "add multiple widgets" to a screen, give the screen a Layout, then add widgets to the layout
GridLayout:
id: some_descriptive_id
rows: 1
Your code is a bit too long to give you an exact solution for your case, but I hope this example gives you the knowledge to fix it up for yourself!

Related

id not being passed to filechooser

I have attached an image showing that the correct filechooser path is being printed out to the console when selecting the file. From that, I assume that the problem is that the self.ids.image.source = filename[0] is failing. Specifically, the id referencing the Image.source. I have tried changing the id and referencing the new one. That doesn't work. I'm still learning Kivy, so I'm not sure if I messed up the hierarchy and I should be calling another id to reference the filechooser's.
Also, I deleted two MDBottomNavigationItems and the contents of the other screens to clean up the code. The question is referring to the LibraryWindow screen.
py file
from kivy.lang import Builder
from kivymd.app import MDApp
from kivy.uix.screenmanager import Screen
from kivy.uix.boxlayout import BoxLayout
# Screens
class LibraryWindow(Screen):
pass
class PlayingWindow(Screen):
pass
class VisualWindow(Screen):
pass
# Top Action Bar
class TopBar(BoxLayout):
pass
# App
class MainApp(MDApp):
def build(self):
self.theme_cls.theme_style = "Dark"
self.theme_cls.primary_palette = "BlueGray"
return Builder.load_file('Z:\\PycharmProjects\\kivyMD\\venv\\my.kv')
def selected(self, filename):
try:
print(filename[0])
self.ids.image.source = filename[0]
except:
pass
MainApp().run()
Kv outline
BoxLayout:
orientation: 'vertical'
TopBar:
MDBottomNavigation:
MDBottomNavigationItem:
name: 'navlib'
text: "Library"
icon: 'book'
LibraryWindow:
#############################
### S C R E E N S ###
#############################
<LibraryWindow>:
name: "library"
size: root.width, root.height
id: my_widget
canvas.before:
Color:
rgba: 0.5,0,0,1
Rectangle:
size: self.size
BoxLayout:
orientation: "vertical"
size: root.width, root.height
padding: 50
spacing: 20
Image:
id: image
source: ''
FileChooserIconView:
id: filechooser
color: 1,.3, .3, 1
on_selection: app.selected(filechooser.selection)
<PlayingWindow>:
<VisualWindow>:
<TopBar>:
Setting an id on the widget that is the root of a rule will not work. The ids are only assigned for children of the widget that is the root of the rule.
Note that the kivy lang documentation confuses the term root widget, using that term for both the root widget of the app and the root widget of a rule. The ids are only set in the ids dictionary of the widget that is the root of the rule where the id appears.
So, you can access the Image widget by adding an id to the LibraryWindow instance in the BoxLayout (the one that is the root of the app) like this:
BoxLayout:
orientation: 'vertical'
TopBar:
MDBottomNavigation:
MDBottomNavigationItem:
name: 'navlib'
text: "Library"
icon: 'book'
LibraryWindow:
id: library
Then you code to set the Image source can become:
self.root.ids.library.ids.image.source = filename[0]
The self.root gets the root widget of the app. The ids.library gets the LibraryWindow instance. The ids.image gets the Image instance that has the image id.

How do I dynamically add widget to grid?

I have a Button in the top boxlayout that I want to add a widget to my grid layout below.
Here is my .py file code
class rootWidget(BoxLayout):
pass
class topWidget(BoxLayout):
print("top part")
class middelWidget(GridLayout):
pass
class bottomWidget(BoxLayout):
pass
class NewButton(Button):
pass
class mainkv(App):
def newButt(self):
print("button clicked")
butt = NewButton(text="New Button")
middelWidget().add_widget(butt)
def build(self):
return rootWidget()
mainkv().run()
And here is my .kv file
<topWidget>:
Button:
text: 'CLick add to grid'
on_press:
app.newButt()
<middelWidget>:
cols: 6
id: grid
Button:
text: 'middel Grid'
<bottomWidget>:
Button:
text: 'bottom'
<rootWidget>:
orientation: 'vertical'
Button:
text: 'Root'
topWidget:
middelWidget:
bottomWidget:
I am not getting any errors but it's not working.
Can't figure out what am missing any help much appreciated.
The problem is that the code:
middelWidget().add_widget(butt)
is creating a new instance of the middelWidget, and adding the Button to that new instance. However, that new instance of middelWidget is not part of your GUI, so nothing happens. The fix is to use the instance of middelWidget that is already in your GUI. That can be done using ids. Here is a modified version of your rootWidget rule in the kv:
<rootWidget>:
orientation: 'vertical'
Button:
text: 'Root'
topWidget:
middelWidget:
id: middle # id for accessing middelWidget
bottomWidget:
Then the newButt() method can be:
def newButt(self):
print("button clicked")
butt = NewButton(text="New Button")
middle = self.root.ids.middle # get a reference to the middelWidget instance
middle.add_widget(butt)
# middelWidget().add_widget(butt)
Also, your classes should begin with and upper case letters. This is not just for appearance, it can cause errors when those classes are used in kv.

Python/Kivy - Sending variables from one class to another

I'm not that new to Python so I have a basic understanding but I wouldn't say that I'm all that great either.
I've been having a tonne of problems with a brazilian jiujitsu app that I'm trying to make in Kivy. I am trying to get the text from a button that has been pressed in one window, and then use that text in a label for the next window that shows. The former window I have given the class name GuardWindow() and the latter window is called SweepSubTranPage().
I have managed to send the name of the button from my kivy file to the class GuardsWindow() easily enough, and the line self.guardlabel = instance.text works fine and retrieves the button name perfectly. My main problem however is sending that name over to the SweepSubTranPage() so that i can access it in my kivy file.
Here is the Python code:
class GuardsWindow(Screen):
guardButtonName = ObjectProperty(None)
def send_guard_type(self, instance, **kwargs):
self.guardButtonName = instance.text # retrieves the button name
def sender(self): # my attempt at sending it to the other class
return self.guardButtonName
class SweepSubTranPage(Screen):
pageTitle = ObjectProperty(None)
gw = GuardsWindow()
pageTitle.text = gw.sender()
kv = Builder.load_file("my.kv")
class MyMainApp(App):
def build(self):
return kv
if __name__ == "__main__":
MyMainApp().run()
And here is the Kivy file code:
<GuardsWindow>
name: "GuardsHomepage"
ScrollView:
bar_width: 10
do_scroll_x: False
do_scroll_y: True
scroll_type: ["bars", "content"]
BoxLayout:
orientation: "vertical"
size_hint: 1, 2
padding: 10
spacing: 10
Button: # these are the buttons that i am getting the text from
text: "Full Guard"
on_press:
root.send_guard_type(self) # this sends the button
on_release:
app.root.current = "SweepSubTranPage"
root.manager.transition.direction = "left"
Button:
text: "Half Guard"
on_press:
root.send_guard_type(self) # this sends the button
on_release:
app.root.current = "SweepSubTranPage"
root.manager.transition.direction = "left"
<SweepSubTranPage>
name: "SweepSubTranPage"
pageTitle: title
BoxLayout:
orientation: "horizontal"
size_hint: 1, 0.1
Label: # this is the label that I need the text for
id: title
font_size: 40
size_hint: 1, 1
When I run the code above, I get the error:
File "C:/Users/bensw/PycharmProjects/BJJ Tracker/main.py", line 36, in <module>
class SweepSubTranPage(Screen):
File "C:/Users/bensw/PycharmProjects/BJJ Tracker/main.py", line 40, in SweepSubTranPage
pageTitle.text = gw.sender()
AttributeError: 'kivy.properties.ObjectProperty' object has no attribute 'text'
I hope I have been clear enough in explaining my issue. If you have any questions please ask!
Thank you so much!!
In your send_guard_type() method you can access another Screen using the manager property of any Screen, and the get_screen() method of the ScreenManager. Something like this:
def send_guard_type(self, instance, **kwargs):
self.guardButtonName = instance.text # retrieves the button name
self.manager.get_screen("SweepSubTranPage").ids.title.text = instance.text

RecycleView and ScreenManager problems

Can't seem to solve getting data from my database to populate into various textinputs when using Recycleview. The problem exist only when i use ScreenManager/Screen. When i call the screen directly from the def build(self): return Screen everything works but not when i call the screen manager like this def build(self): return ScreenManager
kv file
<Button>:
on_press: app.root.get_data(*args)
<Screen>:
BoxLayout:
orientation: 'vertical'
size_hint_x: .3
RV:
viewclass: 'Button'
data: [{'text': str(x)} for x in root.my_data]
RecycleBoxLayout:
orientation: 'vertical'
default_size: None, dp(32)
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
The method get_data() and variable, my_data are implemented in class Screen. Without ScreenManager, the root is Screen. After adding ScreenManager, now the root is ScreenManager. In order to access the method get_data() from the class rule, Button, you need to do the following:
Add id: screen_rv after you have instantiated class rule, <Screen> under ScreenManager
Replace app.root.get_data(*args) with app.root.ids.screen_rv.get_data(*args)
kv - Snippets
<ScreenManagement>:
ScreenRV:
id: screen_rv
<Button>:
on_press: app.root.ids.screen_rv.get_data(*args)
<ScreenRV>:
name: 'screen_rv'

How to get/pass current ScreenManager to button callback function? (no kv file in use)

Question is simple. I have ScreenManager as sm variable, how do I get that, and screen information in to button callback. Thank you already for possible solutions.
Below is the issue part of my code, I have commented the section that I need to solve:
def build(self):
def callback_home(dt):
# How do I get the current sreenmanager here so
# things would work as below
sm.switch_to(screen1, direction='left')
app = FloatLayout()
# Ui top
anchor_top = AnchorLayout(anchor_x='center', anchor_y='top')
app.add_widget(anchor_top)
box_top = BoxLayout(orientation='horizontal',
size_hint=(1.0, 0.1))
anchor_top.add_widget(box_top)
btn_home = Button(text='Home')
btn_home.bind(on_press=callback_home) #Callback line is in here
btn_add = Button(text='Add')
btn_upload = Button(text='Upload')
box_top.add_widget(btn_home)
box_top.add_widget(btn_add)
box_top.add_widget(btn_upload)
# Ui bottom
anchor_bottom = AnchorLayout(anchor_x='center', anchor_y='bottom')
app.add_widget(anchor_bottom)
sm = ScreenManager(size_hint=(1.0, 0.9))
anchor_bottom.add_widget(sm)
screen1 = Screen(name='Home')
screen1.add_widget(Label(text='Home'))
sm.add_widget(screen1)
screen2 = Screen(name='Add')
screen2.add_widget(Label(text='Add'))
sm.add_widget(screen2)
screen3 = Screen(name='Upload')
screen3.add_widget(Label(text='Upload'))
sm.add_widget(screen3)
return app
Define your callback function after your create the ScreenManager. But this is 10 times easier if you use kv language.
Also - ScreenManager.switch_to() only works with new Screens. Using this method to switch to a Screen which has already been added to a ScreenManager will throw an Exception.
Finally, your layout can be much simpler if you use a BoxLayout instead of a FloatLayout and AnchorLayouts.
BoxLayout:
orientation: 'vertical'
BoxLayout:
size_hint_y: 0.1
Button:
text: 'Home'
on_press: sm.current = 'Home'
Button:
text: 'Add'
on_press: sm.current = 'Add'
ScreenManager:
id: sm
Screen:
name: 'Home'
Label:
text: 'Home'
Screen:
name: 'Add'
Label:
text: 'Add'

Resources