I am trying to make a screen view with buttons. The problem is that the amount of buttons needed each time will change, therefore I am not able to use the kv file to make theses buttons. I am having trouble adding buttons through the normal python code. Any help is appreciated.
import kivy
import webbrowser
import MSQLHandler
kivy.require('1.10.0')
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Label
from kivy.uix.widget import Widget
from kivy.uix.listview import ListItemButton
from kivy.properties import ObjectProperty
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen, SlideTransition, CardTransition, SwapTransition, FadeTransition, WipeTransition, FallOutTransition, RiseInTransition, NoTransition
from kivy.lang import Builder
from kivy.uix.button import Button
class Login_Failed(Screen):
def changeScreen(self, next_screen):
self.manager.current = next_screen
class Loged_In(Screen):
def changeScreen(self, next_screen):
self.manager.current = next_screen
class Registers(Screen):
def changeScreen(self, next_screen):
self.manager.current = next_screen
class Login_Screen(Screen):
teacher_connect_image = ObjectProperty()
username_text_input = ObjectProperty()
password_text_input = ObjectProperty()
teacherid_text_input = ObjectProperty()
def LoginButton(self):
if self.teacherid_text_input.text == "":
Number = 0
else:
Number = int(self.teacherid_text_input.text)
MSQLHandler.LoginSystem(self.username_text_input.text, self.password_text_input.text, Number)
def changeScreen(self, next_screen):
self.manager.current = next_screen
if MSQLHandler.LoginSystem(self.username_text_input.text, self.password_text_input.text, Number) is True:
print("Returns True")
changeScreen(self, "Loged_In")
elif MSQLHandler.LoginSystem(self.username_text_input.text, self.password_text_input.text, Number) is False:
print("Returns False")
changeScreen(self, "Login_Failed")
else:
print("Null")
class ScreenManagerr(ScreenManager):
pass
class MainKivyFrameApp(App):
def build(self):
Registers().add_widget(Button(text="Helpp"))
return ScreenManagerr()
mainFrame = MainKivyFrameApp()
mainFrame.run()
If you look to where the app is being built, you will see: Registers().add_widget(Button(text="Helpp"))
This is where I have tried to add a Button to the screen of Registers. This doesn't give me any errors, but it still does not show the button.
Solution
In the kv file, add an event (on_enter or on_pre_enter) in each screen and bind it to a callback method as shown in the following snippets and example. Remember to remove the widgets that were added dynamically before leaving the current screen, by adding an event (on_leave or on_pre_leave).
Snippets
<Registers>:
on_pre_enter: self.add_buttons(n)
on_leave: self.remove_buttons()
Example
main.py
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.button import Button
from kivy.core.window import Window
from kivy.properties import ObjectProperty, NumericProperty
class MyScreenManager(ScreenManager):
total_button = NumericProperty(2)
class Login(Screen):
login = ObjectProperty(None)
def on_pre_enter(self):
Window.size = (400, 300)
def check_password(self, instance, password):
if password == "pwd":
instance.current = "registers"
class Registers(Screen):
container = ObjectProperty(None)
def on_pre_enter(self):
Window.size = (800, 600)
def add_buttons(self, n):
print("Registers: n={}".format(n))
for i in range(n):
self.container.add_widget(Button(text="Button #{}".format(i), id=str(i)))
def remove_buttons(self, *args):
for child in [child for child in self.container.children]:
self.container.remove_widget(child)
class Welcome(Screen):
pass
class TestApp(App):
title = "ScreenManager - Add Widgets Dynamically"
def build(self):
return MyScreenManager()
if __name__ == "__main__":
TestApp().run()
test.kv
#:kivy 1.10.0
#:import SwapTransition kivy.uix.screenmanager.SwapTransition
<MyScreenManager>:
transition: SwapTransition()
Login:
Registers:
on_pre_enter:
self.add_buttons(app.root.total_button)
on_leave:
self.remove_buttons()
Welcome:
<Login>:
id: login
name: "login"
login: login
GridLayout:
size_hint: (0.5, 0.5)
pos_hint: {"center_x": 0.5, "center_y": 0.6}
rows: 3
padding: 20
Label:
size_hint: (0.2, 0.2)
text:"Password:"
font_size: 30
halign: "center"
valign: "middle"
TextInput:
id: password
size_hint: (0.2, 0.06)
cursor_blink: True
font_size: 20
multiline: False
password: True
Button:
text: "Continue"
size_hint: (0.2, 0.08)
on_release:
root.login.check_password(root.manager, password.text)
<Registers>:
name:'registers'
container: container
BoxLayout:
orientation: 'vertical'
Button:
text: 'Return to Login'
on_press: root.manager.current = 'login'
Button:
text: 'Next Screen'
on_press: root.manager.current = 'welcome'
BoxLayout:
id: container
orientation: 'vertical'
<Welcome>:
name:'welcome'
BoxLayout:
Label:
text: 'Welcome!'
Button:
text: 'Return to Registers'
on_press:
app.root.total_button = 5
root.manager.current = 'registers'
Output
Related
I'm very new to Kivy and have been constantly running into issues and errors. A common problem I have is running a python program, seeing that the .kv file is displaying a window, but there is nothing inside the window. The purpose of the code is to display a window starting on the LoginScreen and switching between a separate HomeScreen with a press of a button. Any solutions would be helpful. Thanks.
Python file:
import os
from kivy.app import App
from kivy.config import Config
Config.set('graphics', 'width', '400')
Config.set('graphics', 'height', '600')
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.popup import Popup
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.stacklayout import StackLayout
from kivy.metrics import dp
from kivy.properties import ObjectProperty, StringProperty, BooleanProperty, Clock
from kivy.graphics.vertex_instructions import Line, Rectangle, Ellipse
from kivy.graphics.context_instructions import Color
#transition_direction = StringProperty('down') <--- Ignore this
class HomeScreen(Screen):
def returnBtn(self):
sm.current = 'LoginScreen'
class LoginScreen(Screen):
email = ObjectProperty(None)
password = ObjectProperty(None)
login_lst = []
passwordStudents = open('passwords/passwordStudents.txt').read()
passwordTeachers = open('passwords/passwordTeachers.txt').read()
passwordAdmin = open('passwords/passwordAdmin.txt').read()
def loginBtn(self):
self.login_lst.append(self.email.text)
self.login_lst.append(self.password.text)
if self.login_lst[0] and self.login_lst[-1] in self.passwordStudents:
print('Student: True')
print('Teacher: False')
print('Admin: False')
self.reset()
self.home()
elif self.login_lst[0] and self.login_lst[-1] in self.passwordTeachers:
print('Student: False')
print('Teacher: True')
print('Admin: False')
self.reset()
self.home()
elif self.login_lst[0] and self.login_lst[-1] in self.passwordAdmin:
print('Student: False')
print('Teacher: False')
print('Admin: True')
self.home()
self.reset()
else:
print('Student: False')
print('Teacher: False')
print('Admin: False')
self.reset()
def reset(self):
self.email.text = ''
self.password.text = ''
def home(self):
#transition_direction = 'down' <--- Ignore this
sm.current = 'HomeScreen'
class WindowManager(ScreenManager):
pass
sm = WindowManager()
screens = [LoginScreen(name='login'), HomeScreen(name='home')]
for screen in screens:
sm.add_widget(screen)
sm.current = 'login'
class MyApp(App):
def build(self):
return sm
if __name__ == '__main__':
MyApp().run()
Kivy file:
<LoginScreen>:
name: "login"
email: email
password: psswrd
BoxLayout:
orientation: "vertical"
Label:
text: "Login"
pos: 0, root.height/3
font_size: 100
GridLayout:
cols: 2
Label:
size_hint: None, None
width: "175dp"
height: "50dp"
text: "Email:"
font_size: 50
TextInput:
id: email
multiline: False
size_hint: None, None
width: "200dp"
height: "50dp"
font_size: (root.width**2 + root.height**2) / 14**4
GridLayout:
cols: 2
Label:
size_hint: None, None
width: "175dp"
height: "50dp"
text: "Password:"
font_size: 50
TextInput:
id: psswrd
multiline: False
size_hint: None, None
width: "200dp"
height: "50dp"
password: True
font_size: (root.width**2 + root.height**2) / 14**4
FloatLayout:
Button:
size_hint: None, None
width: "150dp"
height: "100dp"
pos: root.width/2 - 150, root.height/4 - 150
text: "Submit"
font_size: 60
on_release:
root.loginBtn()
<HomeScreen>:
name: "home"
Button:
text: "Go back"
on_release:
root.returnBtn()
Edit: I have noticed that the code runs when I comment out these three lines. Why is that?
class MyApp(App):
#def build(self):
# return sm
pass
#if __name__ == '__main__':
MyApp().run()
You are building your screens before your kv file is loaded, so the LoginScreen and the HomeScreen have nothing in them. If your kv file is correctly named (my.kv) then it will be automatically loaded when MyApp().run() is run and you can build your screens inside the build() method. If your kv file is not named that way, you can just add a call to Builder.load_file() in your build() method before your create the screens.
I'm coding a book reader app with kivymd. I tryied making a MDList with the avaliable chapters and a button to download in every ListItem.
This is a piece of my code:
from kivy.uix.screenmanager import ScreenManager, Screen
from kivymd.uix.list import TwoLineListItem
from kivy.lang import Builder
from kivymd.uix.list import IconRightWidget
class Library(Screen):
pass
class Book(Screen):
pass
class SM(ScreenManager):
pass
KV = '''
SM:
Library:
Book:
<Library>:
MDFloatingActionButton:
pos_hint: {"center_x": 0.5, "center_y": 0.5}
on_release:
app.root.current = "book"
app.list_chapters()
<Book>:
name: "book"
MDBoxLayout:
orientation: "vertical"
MDToolbar:
id: toolbar
ScrollView:
MDList:
id: chap
'''
class Aplication(MDApp):
def build(self):
screen = Builder.load_string(KV)
self.chaps = True
return screen
def list_chapters(self):
if self.chaps:
for chap in range(0, 11):
chapter = TwoLineListItem(text= f'Chapter {chap}')
rightIcon = IconRightWidget(icon="arrow-down-circle-outline")
self.root.get_screen("book").ids.chap.add_widget(chapter)
chapter.add_widget(rightIcon)
self.chaps = False
Aplication().run()
For some reason, all of the IconRightWidget Buttons are getting in the corner of the last TwoListItem. What should I do?
Is there a way to reference a custom widget from the py file?
I made a widget in kv, but I want to reference it from py, then add it again to another widget in kv.
I tried doing this using id but I got an error (KeyError: 'words_entry').
This is what I tried:
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder
from kivy.properties import ObjectProperty
from kivy.uix.textinput import TextInput
import os
class GetCount(Screen):
count_input = ObjectProperty(None)
def next(self):
# Setup next screen
text_inputs = [self.ids.words_entry for i in range(int(self.count_input.text))]
for text_input in text_inputs:
self.manager.ids.get_input.ids.grid.add_widget(text_input)
# Switch to next screen
self.manager.current = "get_input"
class GetInput(Screen):
pass
kv_file = Builder.load_string("""
ScreenManager:
GetCount:
name: "get_count"
id: get_count
GetInput:
name: "get_input"
id: get_input
<WordEntry#TextInput>:
id: words_entry
multiline: False
size_hint: (self.width, None)
<GetCount>:
count_input: count_input
FloatLayout:
Label:
text: "count"
size_hint: 1, 0.05
pos_hint: {"top":0.9}
TextInput:
id: count_input
size_hint: 0.8, 0.05
pos_hint: {"top":0.7, "x":0.1}
multiline: False
Button:
text: "Next"
on_release: root.next()
size_hint: 0.8, 0.05
pos_hint: {"top":0.5, "x":0.1}
<GetInput>:
ScrollView:
GridLayout:
size_hint_y: None
height: self.minimum_height
id: grid
cols: 1
""")
class MainApp(App):
def build(self):
return kv_file
if __name__ == "__main__":
app = MainApp()
app.run()
In this code, I want to add WordEntry to the GridLayout in GetInput from py (the reason is that I need to add multiple depending on the user's input).
You can use Factory to create an instance of a class that has been defined in kv. So your GetCount class can be:
from kivy.factory import Factory
class GetCount(Screen):
count_input = ObjectProperty(None)
def next(self):
# Setup next screen
for _ in range(int(self.count_input.text)):
new_word_entry = Factory.WordEntry()
self.manager.ids.get_input.ids.grid.add_widget(new_word_entry)
# Switch to next screen
self.manager.current = "get_input"
I'm new to kivy and python so my code isn't perfect.
I'm trying to make a program with 2 screens, a first screen where there is a label with a text that is not defined and that can change and a second screen that keeps the same text as the first screen.
I've been searching for a week and I tried to make a global variable that I edit and that becomes the text of the second label but it doesn't work.
I also tried with String. property () or object. property () but I didn't get any more results and I didn't really understand how to use it.
Any help would be welcome <3
(sorry for my english)
Here is a part of my code that I have simplified as much as possible:
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label
from kivy.core.window import Window
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
Builder.load_string("""
<MenuScreen>:
label_wid : ratio
FloatLayout:
Button:
text: "options"
pos: 270, 240
size_hint: .30, .10
background_color: 0,1,0,0.75
on_press: root.manager.current = 'settings'
Label:
id:ratio
text: ""
pos: 0,90
font_size:30
color:1,0,0,1
<SettingsScreen>:
label_wid2 : ratio
FloatLayout:
Label:
id:ratio
text: str(root.texte2())
pos: 0,90
font_size:30
color:1,0,0,1
""")
u=""
class MenuScreen(Screen):
def texte(self):
global u
u= self.label_wid.text = 'exemple'
pass
class SettingsScreen(Screen):
def texte2(self):
self.label_wid2.text=u
pass
class Quizz(App):
def build(self):
self.title = 'Quizz'
Window.clearcolor = (0, 1, 1, 0.25)
return sm
sm = ScreenManager()
sm.add_widget(MenuScreen(name='menu'))
sm.add_widget(SettingsScreen(name='settings'))
if __name__ == '__main__':
Quizz().run()
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label
from kivy.core.window import Window
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
Builder.load_string("""
<MenuScreen>:
label_wid : ratio
FloatLayout:
Button:
text: "options"
pos: 270, 240
size_hint: .30, .10
background_color: 0,1,0,0.75
on_press: root.manager.current = 'settings'
Label:
id:ratio
text: ""
pos: 0,90
font_size:30
color:1,0,0,1
<SettingsScreen>:
label_wid : ratio
FloatLayout:
Label:
id:ratio
text: root.texte2()
pos: 0,90
font_size:30
color:1,0,0,1
""")
u=""
class MenuScreen(Screen):
def texte(self):
global u
u= self.label_wid.text = 'exemple'
pass
class SettingsScreen(Screen):
def texte2(self, text):
u
pass
class Quizz(App):
def build(self):
self.title = 'Quizz'
Window.clearcolor = (0, 1, 1, 0.25)
return sm
sm = ScreenManager()
sm.add_widget(MenuScreen(name='menu'))
sm.add_widget(SettingsScreen(name='settings'))
if __name__ == '__main__':
Quizz().run() ```
Using a StringProperty in the ScreenManager and another in SettingsScreen provide a source of text for both Labels in the different Screens. And changing the StringProperty can change both Labels:
from kivy.app import App
from kivy.clock import Clock
from kivy.properties import StringProperty
from kivy.core.window import Window
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
class MenuScreen(Screen):
pass
class SettingsScreen(Screen):
# this is the text to be used when the first Label text is not '1'
theOtherText = StringProperty('Not One')
class MyScreenManager(ScreenManager):
# This is the text that both Labels may display
theText = StringProperty('0')
kv = """
MyScreenManager:
MenuScreen:
name: 'menu'
SettingsScreen:
name: 'settings'
<MenuScreen>:
label_wid : ratio
FloatLayout:
Button:
text: "options"
pos: 270, 240
size_hint: .30, .10
background_color: 0,1,0,0.75
on_press: root.manager.current = 'settings'
Label:
id:ratio
# Use theText Property from MyScreenManager
text: root.manager.theText
pos: 0,90
font_size:30
color:1,0,0,1
<SettingsScreen>:
label_wid : ratio
FloatLayout:
Label:
id:ratio
# Use theText Property from MyScreenManager
text: '1' if root.manager.theText == '1' else root.theOtherText
pos: 0,90
font_size:30
color:1,0,0,1
"""
class Quizz(App):
def build(self):
self.title = 'Quizz'
Window.clearcolor = (0, 1, 1, 0.25)
Clock.schedule_once(self.change_text, 4)
return Builder.load_string(kv)
def change_text(self, dt):
print('changing text')
self.root.theText = '1'
if __name__ == '__main__':
Quizz().run()
Building the MyScreenManager in the kv eliminates the need to check if the manager attribute of the Screens is set. That simplifies the logic in the kv. Then the line in kv:
text: '1' if root.manager.theText == '1' else root.theOtherText
sets the text of the second Label to 1 if the first Label text is 1, otherwise it is set to the value of theOtherText in the SettingsScreen.
I have added a Clock.schedule_once() just for testing.
So this is the basic code of my tab item.
import kivy
from kivy.app import App
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.uix.gridlayout import GridLayout
Builder.load_string("""
<Test>:
size_hint: .8, .5
pos_hint: {'center_x': .4, 'center_y': .3}
do_default_tab: False
TabbedPanelItem:
text: 'Tab 1'
Label:
text: 'Syntax'
TabbedPanelItem:
text: 'Changeover'
TabbedPanelItem:
text: 'Map'
""")
class Test(TabbedPanel):
pass
class TabbedPanelApp(App):
def build(self):
return Test()
if __name__ == '__main__':
TabbedPanelApp().run()
and i want to insert spinner on Tab 1, how to make it work? this is my spinner code.
from kivy.base import runTouchApp
from kivy.lang import Builder
from kivy.factory import Factory
from kivy.properties import ListProperty, ObjectProperty
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
import kivy
from kivy.app import App
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
class MultiSelectSpinner(Button):
dropdown = ObjectProperty(None)
values = ListProperty([])
selected_values = ListProperty([])
def __init__(self, **kwargs):
self.bind(dropdown=self.update_dropdown)
self.bind(values=self.update_dropdown)
super(MultiSelectSpinner, self).__init__(**kwargs)
self.bind(on_release=self.toggle_dropdown)
def toggle_dropdown(self, *args):
if self.dropdown.parent:
self.dropdown.dismiss()
else:
self.dropdown.open(self)
def update_dropdown(self, *args):
if not self.dropdown:
self.dropdown = DropDown()
values = self.values
if values:
if self.dropdown.children:
self.dropdown.clear_widgets()
for value in values:
b = Factory.MultiSelectOption(text=value)
b.bind(state=self.select_value)
self.dropdown.add_widget(b)
def select_value(self, instance, value):
if value == 'down':
if instance.text not in self.selected_values:
self.selected_values.append(instance.text)
else:
if instance.text in self.selected_values:
self.selected_values.remove(instance.text)
def on_selected_values(self, instance, value):
if value:
self.text = ', '.join(value)
else:
self.text = ''
kv = '''
BoxLayout:
orientation: 'vertical'
size_hint: .7, .6
pos_hint: {'center_x': .3, 'center_y': .7}
do_default_tab: False
BoxLayout:
Label:
text: 'Food Type'
MultiSelectSpinner:
values: 'Fried Chicken', 'Burger'
<MultiSelectOption#ToggleButton>:
size_hint: 8, None
height: '40dp'
'''
runTouchApp(Builder.load_string(kv))
i need abit pointer please
i try to merge the code but not working.
glad if someone can help
i think its best if you create a custom TabbledPanelItem. and then implement that spinner in it.forgive my indentation
class Mod(TabbedPanelItem):
one = ObjectProperty(None)
def __init__(self,**kwargs):
super(Mod,self).__init__(**kwargs)
def on_touch_down(self, touch):
if self.state == 'down':
# dispatch to children, not to self
for child in self.children:
child.dispatch('on_touch_down', touch)
return
else:
super(Mod, self).on_touch_down(touch)
def on_release(self, *largs):
if self.parent:
self.parent.tabbed_panel.switch_to(self)
print(self.parent.children)
lola = MultiSelectSpinner()
lola.toggle_dropdown()
else:
# tab removed before we could switch to it. Switch back to
# previous tab
self.panel.switch_to(self.panel.current_tab)