I created a GUI based off this question while trying to teach myself how to use jsonstore. I don't have the reputation points to add a comment so I'm asking my question here. I think I have the basic idea down but for some reason I can't save the data to a json file. I get the following error:
AttributeError: 'NoneType' object has no attribute 'text'
I've tried following the documentation but I can't see anywhere where it would explain what I'm doing wrong.
main.py
from kivy.storage.jsonstore import JsonStore
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.core.window import Window
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.widget import Widget
from kivy.properties import BooleanProperty, ListProperty, StringProperty, ObjectProperty
Window.clearcolor = (0.02745098, 0.074509804, 0.121568627, 1)
Window.size = (2000, 900)
class TitleScreen(Screen):
pass
class MainScreen(Screen):
pass
class CreateProfile(Screen):
First = ObjectProperty()
Middle = ObjectProperty()
Last = ObjectProperty()
def __init__(self, **kwargs):
super(CreateProfile, self).__init__(**kwargs)
self.store = JsonStore("bco.json")
self.load()
def save(self):
self.store.put('profile', first = self.label.text)
self.store.put('profile', middle = self.label.text)
self.store.put('profile', last = self.label.text)
def load(self):
try:
self.Last.text = self.store.get('profile')['score']
except KeyError:
pass
class CreatePacket(Screen):
pass
class ScreenManagement(ScreenManager):
pass
presentation = Builder.load_file("customwidget.kv")
class CustomWidgetApp(App):
def build(self):
return presentation
if __name__ == "__main__":
CustomWidgetApp().run()
customwidget.kv
#: import FadeTransition kivy.uix.screenmanager.FadeTransition
#: import hex kivy.utils.get_color_from_hex
#: import FocusBehaviors kivy.uix.behaviors.focus
ScreenManagement:
transition: FadeTransition()
TitleScreen:
MainScreen:
CreateProfile:
CreatePacket:
<MainLabel#Label>:
font_size:50
bold: True
size_hint_x: 1
size_hint_y: 1.85
color: 0.396078431, 0.803921569, 0.807843137, 1
font_name: '/home/jarren/PycharmProjects/BCO_Form_Filler/practice/pirulen rg.ttf'
<SubLabel#Label>:
font_size: 35
bold: True
halign: "center"
size_hint_x: 1
size_hint_y: 1.5
color: 0.396078431, 0.803921569, 0.807843137, 1
font_name: '/home/jarren/PycharmProjects/BCO_Form_Filler/practice/pirulen rg.ttf'
<OtherLabel#Label>:
font_size: 12
bold: True
color: 0.396078431, 0.803921569, 0.807843137, 1
font_name: '/home/jarren/PycharmProjects/BCO_Form_Filler/practice/pirulen rg.ttf'
text_size: self.size
<Button#Button>:
font_size: 20
bold: True
color: 0.396078431, 0.803921569, 0.807843137, 1
font_name: '/home/jarren/PycharmProjects/BCO_Form_Filler/practice/pirulen rg.ttf'
background_color: 0.02745098, 0.074509804, 0.121568627, .01
canvas.before:
Color:
rgba: 0.396078431, 0.803921569, 0.807843137, 1
Line:
width: 2
rectangle: self.x, self.y, self.width, self.height
on_press: self.background_color = (0.396078431, 0.803921569, 0.807843137, 1)
on_release: self.background_color = (0.02745098, 0.074509804, 0.121568627, .01)
# TODO: Create a focus behavior to "Tab" between widgets
<TextInput#TextInput>:
font_size: 12
color: 0.396078431, 0.803921569, 0.807843137, 1
font_name: '/home/jarren/PycharmProjects/BCO_Form_Filler/practice/pirulen rg.ttf'
padding_x: 10
padding_y: 10
focus_next: None
focus_previous: None
unfocus_on_touch: True
background_color: 0.02745098, 0.074509804, 0.121568627, .01
canvas.before:
Color:
rgba: 0.396078431, 0.803921569, 0.807843137, 1
Line:
width: 1
rectangle: self.x, self.y, self.width, self.height
<TitleScreen>:
id: "title"
FloatLayout:
MainLabel:
text: "Easy Button"
size_hint_x: 1
size_hint_y: 1.25
SubLabel:
text: 'Test'
size_hint_x: 1
size_hint_y: 1
Button:
text: "Click Here To Continue"
on_release: app.root.current = "main"
size_hint: (.75, .15)
pos_hint: {'x': .12, 'y': .2}
<MainScreen>:
name: "main"
MainLabel:
text: "Home Page"
BoxLayout:
Button:
on_release: app.root.current = "create_profile"
text: "Create Profile"
size_hint: (.5, .15)
Button:
on_release: app.root.current = "create_packet"
text: "Create Packet"
size_hint: (.5, .15)
<CreateProfile>:
name: "create_profile"
AnchorLayout:
anchor_x: 'center'
anchor_y: 'top'
MainLabel:
text: "Create Profile"
size_hint: (1, .15)
BoxLayout:
size_hint: (.95, .2)
pos_hint: {'x': 0, 'y': .85}
spacing: 10
padding: 10
halign: "left"
OtherLabel:
text: "First"
OtherLabel:
text: "Middle"
OtherLabel:
text: "Last"
BoxLayout:
size_hint: (.95, .07)
pos_hint: {'x': 0, 'y': .8}
spacing: 20
padding: 10
halign: "right"
text_size: self.size
TextInput:
id: 'First'
TextInput:
id: "Middle"
TextInput:
id: 'Last'
BoxLayout:
Button:
on_release: app.root.current = "main"
text: "back Home"
size_hint: (.5, .15)
Button:
on_release: root.save()
text: "Save Profile"
size_hint: (.5, .15)
<CreatePacket>:
name: "create_packet"
MainLabel:
text: "Select Packet"
FloatLayout:
Button:
on_release: app.root.current = "main"
text: "back Home"
size_hint: (1, .15)
Your code has several problems but the main one is that you do not understand how to expose any .kv widget to .py, one of the simplest ways is to use an ObjectProperty as you try to do but that property is not linked to the widget, I prefer to do the creation in the .kv for its simplicity.
On the other hand I recommend you avoid the abuse of try-except since it hides errors, the best thing is to verify.
Another error is that you are overwriting the value of profile in the .json, the idea is to save everything in one.
Considering the above, the solution is:
*.py
from kivy.app import App
from kivy.storage.jsonstore import JsonStore
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.core.window import Window
from kivy.clock import Clock
Window.clearcolor = (0.02745098, 0.074509804, 0.121568627, 1)
Window.size = (2000, 900)
class TitleScreen(Screen):
pass
class MainScreen(Screen):
pass
class CreateProfile(Screen):
def __init__(self, **kwargs):
super(CreateProfile, self).__init__(**kwargs)
self.store = JsonStore("bco.json")
Clock.schedule_once(lambda *args: self.load())
def save(self):
self.store.put('profile',
first = self.first.text,
middle = self.middle.text,
last = self.last.text)
def load(self):
if self.store.exists('profile'):
profile = self.store.get('profile')
v = [("first", self.first), ("middle", self.middle), ("last", self.last)]
for key, ti in v:
val = profile.get(key)
if val:
ti.text = val
class CreatePacket(Screen):
pass
class ScreenManagement(ScreenManager):
pass
presentation = Builder.load_file("customwidget.kv")
class CustomWidgetApp(App):
def build(self):
return presentation
if __name__ == "__main__":
CustomWidgetApp().run()
*.kv
#: import FadeTransition kivy.uix.screenmanager.FadeTransition
#: import hex kivy.utils.get_color_from_hex
#: import FocusBehaviors kivy.uix.behaviors.focus
ScreenManagement:
transition: FadeTransition()
TitleScreen:
MainScreen:
CreateProfile:
CreatePacket:
<MainLabel#Label>:
font_size:50
bold: True
size_hint_x: 1
size_hint_y: 1.85
color: 0.396078431, 0.803921569, 0.807843137, 1
font_name: '/home/jarren/PycharmProjects/BCO_Form_Filler/practice/pirulen rg.ttf'
<SubLabel#Label>:
font_size: 35
bold: True
halign: "center"
size_hint_x: 1
size_hint_y: 1.5
color: 0.396078431, 0.803921569, 0.807843137, 1
font_name: '/home/jarren/PycharmProjects/BCO_Form_Filler/practice/pirulen rg.ttf'
<OtherLabel#Label>:
font_size: 12
bold: True
color: 0.396078431, 0.803921569, 0.807843137, 1
font_name: '/home/jarren/PycharmProjects/BCO_Form_Filler/practice/pirulen rg.ttf'
text_size: self.size
<Button#Button>:
font_size: 20
bold: True
color: 0.396078431, 0.803921569, 0.807843137, 1
font_name: '/home/jarren/PycharmProjects/BCO_Form_Filler/practice/pirulen rg.ttf'
background_color: 0.02745098, 0.074509804, 0.121568627, .01
canvas.before:
Color:
rgba: 0.396078431, 0.803921569, 0.807843137, 1
Line:
width: 2
rectangle: self.x, self.y, self.width, self.height
on_press: self.background_color = (0.396078431, 0.803921569, 0.807843137, 1)
on_release: self.background_color = (0.02745098, 0.074509804, 0.121568627, .01)
# TODO: Create a focus behavior to "Tab" between widgets
<TextInput#TextInput>:
font_size: 12
color: 0.396078431, 0.803921569, 0.807843137, 1
font_name: '/home/jarren/PycharmProjects/BCO_Form_Filler/practice/pirulen rg.ttf'
padding_x: 10
padding_y: 10
focus_next: None
focus_previous: None
unfocus_on_touch: True
background_color: 0.02745098, 0.074509804, 0.121568627, .01
canvas.before:
Color:
rgba: 0.396078431, 0.803921569, 0.807843137, 1
Line:
width: 1
rectangle: self.x, self.y, self.width, self.height
<TitleScreen>:
id: "title"
FloatLayout:
MainLabel:
text: "Easy Button"
size_hint_x: 1
size_hint_y: 1.25
SubLabel:
text: 'Test'
size_hint_x: 1
size_hint_y: 1
Button:
text: "Click Here To Continue"
on_release: app.root.current = "main"
size_hint: (.75, .15)
pos_hint: {'x': .12, 'y': .2}
<MainScreen>:
name: "main"
MainLabel:
text: "Home Page"
BoxLayout:
Button:
on_release: app.root.current = "create_profile"
text: "Create Profile"
size_hint: (.5, .15)
Button:
on_release: app.root.current = "create_packet"
text: "Create Packet"
size_hint: (.5, .15)
<CreateProfile>:
name: "create_profile"
first: first
middle: middle
last: last
AnchorLayout:
anchor_x: 'center'
anchor_y: 'top'
MainLabel:
text: "Create Profile"
size_hint: (1, .15)
BoxLayout:
size_hint: (.95, .2)
pos_hint: {'x': 0, 'y': .85}
spacing: 10
padding: 10
halign: "left"
OtherLabel:
text: "First"
OtherLabel:
text: "Middle"
OtherLabel:
text: "Last"
BoxLayout:
size_hint: (.95, .07)
pos_hint: {'x': 0, 'y': .8}
spacing: 20
padding: 10
halign: "right"
text_size: self.size
TextInput:
id: first
TextInput:
id: middle
TextInput:
id: last
BoxLayout:
Button:
on_release: app.root.current = "main"
text: "back Home"
size_hint: (.5, .15)
Button:
on_release: root.save()
text: "Save Profile"
size_hint: (.5, .15)
<CreatePacket>:
name: "create_packet"
MainLabel:
text: "Select Packet"
FloatLayout:
Button:
on_release: app.root.current = "main"
text: "back Home"
size_hint: (1, .15)
I found a work around that still allows me to append information into a JSON by using TinyDB. Here is the updated code:
from kivy.app import App
from kivy.storage.jsonstore import JsonStore
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.core.window import Window
from tinydb import TinyDB, Query
from kivy.uix.listview import ListItemButton
Window.clearcolor = (0.02745098, 0.074509804, 0.121568627, 1)
Window.size = (2000, 900)
db = TinyDB('bcodb.json')
class ProfileListButton(ListItemButton):
pass
class TitleScreen(Screen):
pass
class MainScreen(Screen):
pass
class CreateProfile(Screen):
def __init__(self, **kwargs):
super(CreateProfile, self).__init__(**kwargs)
self.store = JsonStore("bcodb.json")
def save(self):
db.insert({'first': self.first.text, 'middle': self.middle.text, 'last': self.last.text})
def update(self):
db.update({'first': self.first.text, 'middle': self.middle.text, 'last': self.last.text})
class CreatePacket(Screen):
pass
class ScreenManagement(ScreenManager):
pass
presentation = Builder.load_file("customwidget2.kv")
class CustomWidgetApp(App):
def build(self):
return presentation
if __name__ == "__main__":
CustomWidgetApp().run()
It's pretty easy to figure out with a simple database-like program I'm trying to develop. The .kv file is the same.
Related
Im trying to add a MDDropDownMenu in my databaseWindow, but each time I try to access the menu, the app crashes with an error of "'databaseWindow' object has no attribute 'menu'". Im planning to use the dropdown menu as a list of options for the user to choose from so they can run a query. Im new to KivyMD and any assistance would be appreciated.
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.uix.screenmanager import ScreenManager,Screen
from kivy.core.window import Window
from kivy.uix.label import Label
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.popup import Popup
from kivymd.uix.datatables import MDDataTable
from kivy.metrics import dp
from kivy.uix.anchorlayout import AnchorLayout
from kivymd.uix.menu import MDDropdownMenu
from kivy.properties import ObjectProperty
import mysql.connector
class myLoginScreen(Screen):
def __init__(self, **kwargs):
super().__init__(**kwargs)
class databaseWindow(Screen):
def dbtable_menu(self):
layout = AnchorLayout()
menu_items = [
{
"text": f"Item {i}",
"right_text": f"R+{i}",
"right_icon": "apple-keyboard-command",
"left_icon": "git",
"viewclass": "Item",
"height": dp(54),
"on_release": lambda x=f"Item {i}": self.menu_callback(x),
} for i in range(5)
]
self.menu = MDDropdownMenu(
caller = self.manager.get_screen('database1').ids['button'],
items = menu_items,
width_mult=4,
)
self.add_widget(self.menu)
def menu_callback(self, text_item):
print(text_item)
self.manager.get_screen('database1').ids['button'].text = str(text_item)
class MainApp(MDApp):
def build(self):
self.screen = Builder.load_file('login3.kv')
sm = ScreenManager()
sm.add_widget(myLoginScreen(name='main'))
sm.add_widget(databaseWindow(name='database1'))
return sm
if __name__ == "__main__":
MainApp().run()
Here is the kivy file:
#:import Window kivy.core.window.Window
#:import utils kivy.utils
ScreenManager:
myLoginScreen:
databaseWindow:
<myLoginScreen>:
id:main
name:'main'
bg_color: (1,1,1,.3)
highlight_color1jbsidis: [0,0,0,0]
highlight_color2jbsidis: (0,0,0,.3)
canvas.before:
Color:
rgba: utils.get_color_from_hex('#0A609E')
Rectangle:
size: self.size
pos: self.pos
FloatLayout:
#Image:
# source: '/Users/logo.png'
# pos_hint: {'right':.99, 'top':.85}
# size_hint_y: None
# height: dp(40)
# size: self.size
# pos: self.pos
# allow_stretch: False
# keep_ratio: True
TextInput:
id: username
hint_text: "Username"
foreground_color: [1,1,1,1]
background_color: [0,0,0,0]
background_image: ""
background_normal: ""
background_active: ""
multiline: False
font_size: 40
size_hint: .7 ,.1 #.06
pos_hint: {'center_x':.5, 'center_y':.65} #'center_y':.8
canvas.before:
Color:
rgba: [1,1,1,.5]
RoundedRectangle:
size: self.size
pos: self.pos
radius: 10,
FloatLayout:
MDIconButton:
text: "[u]Reset password[/u]"
icon: 'account'
markup: True
color: Window.clearcolor
opposite_colors: True
pos_hint: {'center_x':.8, 'center_y':.65}
TextInput:
id: password
hint_text: "Password"
foreground_color: [1,1,1,1]
background_color: [0,0,0,0]
background_image: ""
background_normal: ""
background_active: ""
multiline: False
password: True
size_hint: .7 ,.1 #.06
font_size: 40
pos_hint: {'center_x':.5, 'center_y':.45}
canvas.before:
Color:
rgba: [1,1,1,.5]
RoundedRectangle:
size: self.size
pos: self.pos
radius: 10,
FloatLayout:
MDIconButton:
icon: 'lock-outline'
markup: True
color: Window.clearcolor
opposite_colors: True
pos_hint: {'center_x':.8, 'center_y':.45}
MDRaisedButton:
id: sign_button
text: "Sign In"
pos_hint: {"center_x": .5, "top": .3}
on_release:
app.root.current = "database1"
MDRaisedButton:
id: button
text: "Sign up"
size_hint: .2 ,.05
pos_hint: {"right": .85, "center_y": .1}
opacity: 1
disabled: False
bg_color: (0,0,0,1)
color: [0,0,0,1]
<databaseWindow>:
id: database1
name: 'database1'
canvas.before:
Color:
rgba: utils.get_color_from_hex('#0A609E')
Rectangle:
size: self.size
pos: self.pos
MDRaisedButton:
id: button
text: "PRESS ME"
pos_hint:{"center_x":.5, "center_y":0.5}
on_release: root.menu.open()
MDTopAppBar:
title: "Select ONLY 1 Row for Query"
pos_hint: {'top':1}
elevation: 5
MDBoxLayout:
orientation: 'vertical'
padding: 10
MDFloatingActionButton:
icon: 'logout-variant'
on_press:
app.root.current = 'main'
root.log_out()
# GUI for pop up window
<P>:
Label:
text : "Please enter valid information"
size_hint : 0.2, 0.1
pos_hint : {"x" : 0.3, "top" : 0.8}
I'm having trouble calling a function in the .kv file. I get " AttributeError: 'ScreenManager' object has no attribute 'text_wait'" with app.root, and "AttributeError: 'FirstScreen' object has no attribute 'text_wait'" with just root. I'm assuming it's something to do with the multiple wnidows that im using, but is there a way to fix this?
kv code:
<FirstScreen>:
canvas:
Color:
rgb: (255/255, 170/255, 235/255)
Rectangle:
pos: self.pos
size: self.size
Line:
width: 2
rectangle: self.x, self.y, self.width, self.height
Button:
id: obama_text
size_hint: (.274, .2)
pos_hint: {"x":.067, "y":.049}
background_normal: ''
background_color: 1, .5, .6, .85
font_size: 50
bold: True
color: 200/255, 0/255, 70/255, 1
text: "OBAMA"
on_release: app.root.text_wait("burger") # gives an error
<SecondScreen>:
FloatLayout:
Button:
text: "Go to third"
pos_hint: {"center_x": .5, "center_y": .5}
size_hint: .2, .2
on_release: root.manager.current = "third"
<ThirdScreen>:
FloatLayout:
Button:
text: "go to fourth"
size_hint: .3, .1
pos_hint: {"x": .3, "y": .5}
on_release: root.manager.current = "fourth"
<FourthScreen>:
FloatLayout:
Button:
text: "go to first"
size_hint: .3, .1
pos_hint: {"x": .3, "y": .5}
on_release: root.manager.current = "first"
.py code:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.core.window import Window
import time
Window.fullscreen = True
Builder.load_file("test.kv")
class FirstScreen(Screen):
pass
class SecondScreen(Screen):
pass
class ThirdScreen(Screen):
pass
class FourthScreen(Screen):
pass
class MainApp(App):
def build(self):
sm = ScreenManager()
sm.add_widget(FirstScreen(name="first"))
sm.add_widget(SecondScreen(name="second"))
sm.add_widget(ThirdScreen(name="third"))
sm.add_widget(FourthScreen(name="fourth"))
return sm
def text_wait(self, text):
#for i in text:
#print(i)
pass
if __name__ == "__main__":
MainApp().run()
The text_wait method is an instance method of the MyApp class. So you simply need to call app.text_wait. You just need to remove the root part of the directive in your .kv file.
<FirstScreen>:
canvas:
Color:
rgb: (255/255, 170/255, 235/255)
Rectangle:
pos: self.pos
size: self.size
Line:
width: 2
rectangle: self.x, self.y, self.width, self.height
Button:
id: obama_text
size_hint: (.274, .2)
pos_hint: {"x":.067, "y":.049}
background_normal: ''
background_color: 1, .5, .6, .85
font_size: 50
bold: True
color: 200/255, 0/255, 70/255, 1
text: "OBAMA"
on_release: app.text_wait("burger") # gives an error
...
I am trying to code a simple quiz game. There're supposed to be multiple screens, the first screen (LoginWindow) being a simple login form. After the login and confirmation of the right name and password being entered the second screen (GameWindow) is supposed to show up, but it doesn't. Right from the start the second screen is being loaded.
I'm sure I am missing something super simple and basic but I just don't get it.
.py file:
from kivy.app import App
from kivy.properties import ObjectProperty
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.uix.screenmanager import ScreenManager, Screen
import hashlib
Window.size = (512, 512)
user_hash = ""
pass_hash = ""
super_user = "9279F4A7C1C145D5AE930FDA23EF386168F6720B4E0F0D3DEE383C5AD8535737"
super_pass = "EE22032527082315A747781829EF1F9195F6AEAC09C0D52DE06EBF9D8C463918"
# Define screens
class LoginWindow(Screen):
name = ObjectProperty(None)
passw = ObjectProperty(None)
def press(self):
user_hash = hashlib.sha256(self.name.text.encode('utf-8')).hexdigest().upper()
pass_hash = hashlib.sha256(self.passw.text.encode('utf-8')).hexdigest().upper()
if (user_hash == super_user) and (pass_hash == super_pass):
print("Das hat geklappt!")
WindowManager.current = 'game'
else:
print("Du kummst hier net rein!")
class GameWindow(Screen):
pass
class WindowManager(ScreenManager):
pass
kv = Builder.load_file('box_multiscreen.kv')
class Affenquiz(App):
def build(self):
Window.clearcolor = (0.8, 0.8, 0.8, 1)
WindowManager = ScreenManager()
WindowManager.add_widget(LoginWindow(name='login'))
WindowManager.add_widget(GameWindow(name='game'))
WindowManager.current = 'login'
return kv
if __name__ == "__main__":
Affenquiz().run()
.kv file:
WindowManager:
LoginWindow:
name: "login"
GameWindow:
name: "game"
<LoginWindow>:
name:name
passw:passw
BoxLayout:
orientation: "vertical"
size: root.width, root.height
spacing: 20
padding: 20
canvas.before:
Rectangle:
pos: self.pos
size: self.size
source: 'monkey.png'
AnchorLayout:
anchor_y: 'top'
BoxLayout:
orientation: "horizontal"
size_hint: (1, None)
height: 50
Label:
text: "Der Quizfelsen"
font_size: 50
BoxLayout:
orientation: "horizontal"
size_hint: (1, None)
height: 50
Label:
text: "Benutzer:"
TextInput:
id: name
multiline:False
background_color: (241/255.0,241/255.0,241/255.0,0.9)
BoxLayout:
orientation: "horizontal"
size_hint: (1, None)
height: 50
Label:
text: "Passwort:"
TextInput:
id: passw
multiline:False
background_color: (241/255.0,241/255.0,241/255.0,0.9)
RoundedButton:
text: "Login"
pos_hint: {'center_x': .5}
size_hint: (1, None)
height: 50
on_press: root.press()
<GameWindow>:
Label:
text: "Der Quizfelsen"
font_size: 50
<Label>
font_size: 32
background_normal: ''
background_color: (0.9,0.9,0.9,0)
canvas.before:
Color:
rgba: self.background_color
Rectangle:
size: self.size
pos: self.pos
color: (184/255.0,70/255.0,35/255.0,1)
bold: True
outline_color: (1,1,1,1)
outline_width: 2
<RoundedButton#Button>
background_color: (0,0,0,0)
background_normal: ''
canvas.before:
Color:
rgba: (184/255.0,70/255.0,35/255.0,0.9)
RoundedRectangle:
size: self.size
pos: self.pos
radius: [25]
Thank you in advance
I am trying to create a checkbox in my float layout area. I am getting the checkbox to generate but every time I click it goes from True to False even if it not on the box. Could someone provide some insight?
My code:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.checkbox import CheckBox
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition
from kivy.uix.textinput import TextInput
from kivy.uix.widget import Widget
#######``Windows``#######
class MainScreen(Screen):
pass
class AnotherScreen(Screen):
def add(self, *args):
a = self.ids["a"].text
a = int(a)
self.ids["adds"]
plus = 1 + a
print plus
class ScreenManagement(ScreenManager):
pass
presentation = Builder.load_file("GUI_Style.kv")
class MainApp(App):
def build(self):
return presentation
if __name__ == "__main__":
MainApp().run()
My KV File:
#: import NoTransition kivy.uix.screenmanager.NoTransition
ScreenManagement:
transition: NoTransition()
MainScreen:
AnotherScreen:
<MainScreen>:
background_color: 0.5, 1, 0.22, 1
name: "main"
FloatLayout:
Button:
text: "Quit"
font_size: 50
color: 0,1,0,1
font_size: 25
size_hint: 0.3,0.2
pos_hint: {"x":0, "y":0}
on_release: app.window().stop()
Button:
on_release: app.root.current = "other"
text: "Next Screen"
font_size: 50
color: 0,1,0,1
font_size: 25
size_hint: 0.3,0.2
pos_hint: {"right":1, "top":1}
<AnotherScreen>:
name: "other"
canvas.before:
Color:
rgba: 1, 1, 1, 1
Rectangle:
pos: self.pos
size: self.size
FloatLayout:
CheckBox:
pos_hint: {"x":0.2, "y":0.2}
on_release: True
TextInput:
id: a
font_size: 25
password: True
pos_hint: {"x":0.5, "y":0.5}
size_hint: 0.3,0.2
text: "Insert Side A here"
Button:
id: adds
background_color: 0,0,1,1
color: 0,1,0,1
font_size: 25
on_release: root.add()
pos_hint: {"x":0, "y":0}
size_hint: 0.3,0.2
text: "plus"
Button:
color: 0,1,0,1
background_color: 0,0,1,1
font_size: 25
size_hint: 0.3,0.2
text: "Back Home"
on_release: app.root.current = "main"
pos_hint: {"right":1, "top":1}
Try placing the CheckBox in a Widget and it works. I mean:
FloatLayout:
Widget:
CheckBox:
pos_hint: {"x":0.2, "y":0.2}
on_release: True
TextInput:
id: a
font_size: 25
password: True
pos_hint: {"x":0.5, "y":0.5}
size_hint: 0.3,0.2
text: "Insert Side A here"
Button:
id: adds
background_color: 0,0,1,1
color: 0,1,0,1
font_size: 25
on_release: root.add()
pos_hint: {"x":0, "y":0}
size_hint: 0.3,0.2
text: "plus"
of course it ruins your layout but it solves the problem you are having.
I was wondering how I could change the text of a label made inside the Kivy language using Python.
Like how would I have user input from python be made as the text of a label in kivy.
(By the way I have the formatting correct in the actual program but I screwed up pasting it to stackoverflow)
Say if I wanted to make the text of the label in from the code be a random number generated in python how would I go about doing that?
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.graphics import Color, Rectangle
from kivy.properties import ObjectProperty
# Create both screens. Please note the root.manager.current: this is how
# you can control the ScreenManager from kv. Each screen has by default a
# property manager that gives you the instance of the ScreenManager used.
Builder.load_string("""
<ButImage#ButtonBehavior+AsyncImage>
<TutImage#ButtonBehavior+AsyncImage>
<MenuScreen>:
GridLayout:
cols: 4
row_force_default: True
col_default_width: 175
row_default_height: 150
padding: 15
spacing: 15
canvas.before:
BorderImage:
# BorderImage behaves like the CSS BorderImage
border: 10, 10, 10, 10
source: '/Users/clayhigh/Desktop/kivy/aot.png'
pos: self.pos
size: self.size
Button:
text: 'Goto settings'
background_color: 1,0,0,0.5
on_press: root.manager.current = 'settings'
ButImage:
on_press: root.manager.current = 'UBW'
id: but
size_hint: .5, .5
opacity: 1 if self.state == 'normal' else .5
allow_stretch: True
keep_ratio: False
source: 'http://s3.amazonaws.com/rapgenius/1361742626_beautiful-ocean-beautiful-pictures-27115524-1440-900.jpg'
Label:
center: but.center
text: "UBW"
color: 0.78,0.145,0.016,2
ButImage:
id: lh
size_hint: .5, .5
opacity: 1 if self.state == 'normal' else .5
allow_stretch: True
keep_ratio: False
source: 'http://s3.amazonaws.com/rapgenius/1361742626_beautiful-ocean-beautiful-pictures-27115524-1440-900.jpg'
Label:
center: lh.center
text: "LH 2"
color: 0,0,0,1
ButImage:
id: ttl
size_hint: .5, .5
opacity: 1 if self.state == 'normal' else .5
allow_stretch: True
keep_ratio: False
source: 'http://s3.amazonaws.com/rapgenius/1361742626_beautiful-ocean-beautiful-pictures-27115524-1440-900.jpg'
Label:
center: ttl.center
text: "TwTl"
color: 0,0,0,1
ButImage:
id: gris
size_hint: .5, .5
opacity: 1 if self.state == 'normal' else .5
allow_stretch: True
keep_ratio: False
source: 'http://s3.amazonaws.com/rapgenius/1361742626_beautiful-ocean-beautiful-pictures-27115524-1440-900.jpg'
Label:
center: gris.center
text: "Gris"
color: 0,0,0,1
ButImage:
id: shig
size_hint: .5, .5
opacity: 1 if self.state == 'normal' else .5
allow_stretch: True
keep_ratio: False
source: 'http://s3.amazonaws.com/rapgenius/1361742626_beautiful-ocean-beautiful-pictures-27115524-1440-900.jpg'
Label:
center: shig.center
text: "Shig"
color: 0,0,0,1
Button:
text: 'Test3'
background_color: 1,0,0,0.5
Button:
text: 'Test4'
background_color: 1,0,0,0.5
Button:
text: 'Quit'
background_color: 1,0,0,0.5
on_press: App.on_stop
<SettingsScreen>:
GridLayout:
row_force_default: True
row_default_height: 100
cols: 2
canvas.before:
BorderImage:
# BorderImage behaves like the CSS BorderImage
border: 10, 10, 10, 10
source: '/Users/clayhigh/Desktop/kivy/ato.jpeg'
pos: self.pos
size: self.size
Button:
text: 'Button'
color: 0,0,.5
background_color: 1,0,0,1
Button:
text: 'Back to menu'
background_color: 1,0,0,1
on_press: root.manager.current = 'menu'
<UBW>:
GridLayout:
row_force_default: True
row_default_height: 100
cols: 2
canvas.before:
Color:
rgb: .5, .5, .5
Rectangle:
pos: self.pos
size: self.size
Color:
rgb: 1, 1, 1
BorderImage:
# BorderImage behaves like the CSS BorderImage
border: 10, 10, 10, 10
source: '/Users/clayhigh/Desktop/kivy/fsn.jpg'
pos: self.pos
size: self.size
Button:
text: 'Back to menu'
color: 0,0,.5
on_press: root.manager.current = 'menu'
background_color: 1,0,0,1
Label:
id: AName
text: "F S/N: UBW"
font_size: '24sp'
""")
# Declare both screens
class MenuScreen(Screen):
pass
class SettingsScreen(Screen):
pass
class UBW(Screen):
pass
# Create the screen manager
sm = ScreenManager()
sm.add_widget(MenuScreen(name='menu'))
sm.add_widget(SettingsScreen(name='settings'))
sm.add_widget(UBW(name='UBW'))
class TestApp(App):
def build(self):
return sm
if __name__ == '__main__':
TestApp().run()
Text of a label can be a kivy property, which can be later changed and since it is a kivy property it will automatically updated everywhere. Here is an example of your .py
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import StringProperty
import random
class YourWidget(Widget):
random_number = StringProperty()
def __init__(self, **kwargs):
super(YourWidget, self).__init__(**kwargs)
self.random_number = str(random.randint(1, 100))
def change_text(self):
self.random_number = str(random.randint(1, 100))
class YourApp(App):
def build(self):
return YourWidget()
if __name__ == '__main__':
YourApp().run()
and your .kv
<YourWidget>:
BoxLayout:
size: root.size
Button:
id: button1
text: "Change text"
on_release: root.change_text()
Label:
id: label1
text: root.random_number
When you click the button, it will call change_text() function, which will randomly change the text of the label to random integer between 1 and 100.