i am working with kivy and i wrote this code.
from kivy.app import App
from kivy.uix.button import Button
from kivy.graphics import Rectangle
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget
class Main(Widget):
def __init__(self,**kwargs):
super().__init__(**kwargs)
pass
def on_press(self):
sub()
class sub(Widget):
def __init__(self,**kwargs):
super().__init__(**kwargs)
pass
class Rect(App):
def build(self):
return Main()
if __name__=='__main__':
Rect().run()
.kv file
<Main>:
FloatLayout:
canvas:
Rectangle:
pos:100,0
size:200,200
Button:
text:'Click'
on_press:root.on_press()
<Sub>:
FloatLayout:
canvas:
Rectangle:
pos:100,0
size:400,400
when i run the code,the window showing rectangle and button opens up. when i click on button, i expect to show a bigger rectangle but nothing actually happens.what should i do to dislay the bigger rectangle which is defined in another class by clicking 'click'.Thanks in advance.
CodePudding user response:
First of all, the code you put here contains some errors, you are instantiating an object called main() instead of the object created Main() with capitalized M, in Rect class.
About what you are wanting, when the action on_press() is called, you are instantiating an object of type sub(), but you are not placing it inside the desired widget, that is, the object is actually being created, but not appears on the screen.
To solve this you need to add this newly created object to your main widget, in that case just call self.add_widget()
The code with the fixes are:
RectApp.py
from kivy.app import App
from kivy.uix.button import Button
from kivy.graphics import Rectangle
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget
class Main(Widget):
def __init__(self,**kwargs):
super().__init__(**kwargs)
pass
def on_press(self):
self.add_widget(Sub())
class Sub(Widget):
def __init__(self,**kwargs):
super().__init__(**kwargs)
pass
class RectApp(App):
def build(self):
return Main()
if __name__=='__main__':
RectApp().run()
rect.kv
<Main>:
FloatLayout:
canvas:
Rectangle:
pos: 100, 0
size: 200, 200
Button:
text: 'click'
on_press: root.on_press()
<Sub>:
FloatLayout:
canvas:
Rectangle:
size: 400, 400
pos: 300, 0