Python - Kivy - Screen Manager - Changing a Button Text with Text Input issue - python

I'm currently working with Kivy for GUI Design I was looking for a way to change a button text with a TextInput from another screen.
My Screen 1 has a button that will work as a "label", there I have another button to go to screen 2.
Screen 2 is a Keypad with a Textinput on it, there I put the numbers that I want to set in the button "label" from screen 1.
With a button called "ENTER" I want to go back to the screen 1 and update the new text in the button "label". But I can't figure out how to do it properly.
Here is a little piece of the project code main.py :
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.uix.label import Label
from kivy.uix.widget import Widget
from kivy.graphics import Line
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
class Main_Screen(Screen):
pass
class Input_Number_Inch_Screen(Screen):
pass
class Input_Screen(Screen):
pass
class Screen_Management(ScreenManager):
pass
presentation = Builder.load_file("screen3.kv")
class Screen3App(App):
def build(self):
return presentation
Screen3App().run()
the screen3.kv file:
Screen_Management:
id: screen_management
transition: FadeTransition()
Main_Screen:
id: main_screen
name: "main_screen_name"
manager: screen_management
Input_Screen:
id: tire_setup_screen_id
name: "tire_setup_screen_name"
manager: screen_management
Input_Number_Inch_Screen:
name: "inch_screen"
manager: screen_management
<Main_Screen>:
canvas:
Color:
rgb: [.30, .30, .30]
Rectangle:
pos: self.pos
size: self.size
Button:
background_color: .52, .52, .52, 1
bold: 1
color: .0078,.67,.69,1
size_hint: .2, 1
pos_hint: {"x": 0, "center_y": .5}
on_release: app.root.current = "tire_setup_screen_name"
text: " INPUTS "
font_size: 30
# Screen 1: Input Screen
<Input_Screen>:
canvas:
Color:
rgb: [.30, .30, .30]
Rectangle:
pos: self.pos
size: self.size
GridLayout:
cols: 2
pos: (160,150)
size_hint: (.8, .8)
Button:
background_color: .52, .52, .52, 1
bold: 1
color: .0078,.67,.69,1
font_size: 30
text: "INPUT\n(Inch)"
size_hint_x: None
width: 150
on_release: app.root.current = "inch_screen"
# This button will go to the screen2
Button:
id: inch_input
background_color: .52, .52, .52, 1
bold: 1
color: .0078,.67,.69,1
font_size: 100
text: "THIS IS THE TEXT THAT I WANT TO UPDATE"
# Screen 2: Input Inch Screen Data
<Input_Number_Inch_Screen>:
canvas:
Color:
rgb: [.30, .30, .30]
Rectangle:
pos: self.pos
size: self.size
GridLayout:
orientation: 'vertical'
display: entry
rows: 6
padding: 10
spacing: 10
# This is the TextInput
BoxLayout:
TextInput:
id: entry
font_size: 75
multiline: False
# This will be the button that would go back to the screen and update
# the button text with the new text entered in the TextInput
BoxLayout:
spacing: 10
Button:
background_color: .52, .52, .52, 1
bold: 1
color: .0078,.67,.69,1
font_size: 40
text:"ENTER"
on_release: app.root.current = "tire_setup_screen_name"
on_press: app.root.inch_input.text = entry.text
Any comment to help it would be great, thanks for your time.

Please replace the following in screen3.kv:
on_press: app.root.inch_input.text = entry.text
with:
on_press: root.manager.ids.tire_setup_screen_id.ids.inch_input.text = entry.text
Example
main.py
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.uix.label import Label
from kivy.uix.widget import Widget
from kivy.graphics import Line
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
class Main_Screen(Screen):
pass
class Input_Number_Inch_Screen(Screen):
pass
class Input_Screen(Screen):
pass
class Screen_Management(ScreenManager):
pass
presentation = Builder.load_file("screen3.kv")
class Screen3App(App):
def build(self):
return presentation
if __name__ == "__main__":
Screen3App().run()
screen3.kv
#:kivy 1.10.0
#:import FadeTransition kivy.uix.screenmanager.FadeTransition
Screen_Management:
id: screen_management
transition: FadeTransition()
Main_Screen:
id: main_screen
name: "main_screen_name"
manager: screen_management
Input_Screen:
id: tire_setup_screen_id
name: "tire_setup_screen_name"
manager: screen_management
Input_Number_Inch_Screen:
name: "inch_screen"
manager: screen_management
<Main_Screen>:
canvas:
Color:
rgb: [.30, .30, .30]
Rectangle:
pos: self.pos
size: self.size
Button:
background_color: .52, .52, .52, 1
bold: 1
color: .0078,.67,.69,1
size_hint: .2, 1
pos_hint: {"x": 0, "center_y": .5}
on_release: root.manager.current = "tire_setup_screen_name"
text: " INPUTS "
font_size: 30
# Screen 1: Input Screen
<Input_Screen>:
canvas:
Color:
rgb: [.30, .30, .30]
Rectangle:
pos: self.pos
size: self.size
GridLayout:
cols: 2
pos: (160,150)
size_hint: (.8, .8)
Button:
background_color: .52, .52, .52, 1
bold: 1
color: .0078,.67,.69,1
font_size: 30
text: "INPUT\n(Inch)"
size_hint_x: None
width: 150
on_release: root.manager.current = "inch_screen"
# This button will go to the screen2
Button:
id: inch_input
background_color: .52, .52, .52, 1
bold: 1
color: .0078,.67,.69,1
font_size: 100
text: "THIS IS THE TEXT THAT I WANT TO UPDATE"
# Screen 2: Input Inch Screen Data
<Input_Number_Inch_Screen>:
canvas:
Color:
rgb: [.30, .30, .30]
Rectangle:
pos: self.pos
size: self.size
GridLayout:
orientation: 'vertical'
display: entry
rows: 6
padding: 10
spacing: 10
# This is the TextInput
BoxLayout:
TextInput:
id: entry
font_size: 75
multiline: False
# This will be the button that would go back to the screen and update
# the button text with the new text entered in the TextInput
BoxLayout:
spacing: 10
Button:
background_color: .52, .52, .52, 1
bold: 1
color: .0078,.67,.69,1
font_size: 40
text:"ENTER"
on_release: root.manager.current = "tire_setup_screen_name"
on_press: root.manager.ids.tire_setup_screen_id.ids.inch_input.text = entry.text
Outpu

Related

I had a problem with creating a popup in kivy with rounded edges

I tried to create a white popup window with rounded edges as the first image by using a canvas, but when I write canvas.after or canvas.before it comes behind or above the popup window content, so how I can make it looks like the first image?
.py file:
from kivy.app import App
from kivy.core.window import Window
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.core.text import LabelBase
from kivy.uix.popup import Popup
Window.size = [300,600]
class MyLayout(Widget):
pass
class Exercise(App):
def build(self):
#Window color
Window.clearcolor = (249/255.0, 249/255.0, 249/255.0, 0)
Builder.load_file("myfile.kv")
#Loading .kv file
return MyLayout()
if __name__ == "__main__":
Exercise().run()
.kv file:
#: import Factory kivy.factory.Factory
<MyPopup#Popup>
auto_dismiss: False
title: ""
separator_height: 0
size_hint: 0.8, 0.4
background_color: (0,0,0,0)
background_normal: ''
canvas.before:
Color:
rgba:(255/255,255/255,255/255,1)
RoundedRectangle:
pos: self.pos
size: self.size
radius: [40]
BoxLayout:
orientation: "vertical"
size: root.width, root.height
padding: 0, 10, 10, 10
border: 50
border_color: (1,1,1,1)
Label:
text: "Good job"
color: 0,0,0,1
font_size: 16
CloseButton:
text: "Close"
color: 0,0,0,1
size_hint: (None , None)
width: 105
height: 40
pos_hint: {'center_x':0.5}
on_release: root.dismiss()
<MyLayout>:
BoxLayout:
orientation: "vertical"
size: root.width, root.height
padding: 20,40
#spacing: 20
Label:
font_size: 20
text: 'Click the button'
color: 0, 0, 0, 1
MyButton:
font_size: 20
text: "Button"
color: (0,0,0,1)
size_hint: (None , None)
width: 250
height: 50
pos_hint: {'center_x':0.5}
on_release: Factory.MyPopup().open()
<CloseButton#Button>:
background_color: (0,0,0,0)
background_normal: ''
canvas.before:
Color:
rgba:(252/255,131/255,87/255,1)
RoundedRectangle:
pos: self.pos
size: self.size
radius: [20]
<MyButton#Button>
background_color: (0,0,0,0)
background_normal: ''
canvas.before:
Color:
rgba:(252/255,131/255,87/255,1)
RoundedRectangle:
pos: self.pos
size: self.size
radius: [25]
Remove the canvas.before from the first part of the Popup and add it to the BoxLayout. Adjust the size and position of the canvas.before to make it cover the default background.
Here is the modified Popup definition that will work.
<MyPopup#Popup>
auto_dismiss: False
title: ""
separator_height: 0
size_hint: 0.8, 0.4
BoxLayout:
orientation: "vertical"
size: root.width, root.height
padding: 0, 10, 10, 10
border: 50
border_color: (1,1,1,1)
canvas.before:
Color:
rgba: 1, 1, 1, 1
RoundedRectangle:
pos: self.x - 20, self.y - 20
size: self.width + 40, self.height + 60
radius: [40]
Label:
text: "Good job"
color: 0,0,0,1
font_size: 16
CloseButton:
text: "Close"
color: 0,0,0,1
size_hint: (None , None)
width: 105
height: 40
pos_hint: {'center_x':0.5}
on_release: root.dismiss()

Kivy self manager get screen - not working

recently I try to make that app with python and kivy. After tons of hours googling everything together i more or less have everything i want. Only one thing is missing:
I have several screens. At the beginning of the App I have a menu. After that i have lots of questions; all of them have the same text and buttons in the bottom of the screen. I managed to make that the following way:
<firstquestion>:
name: "firstquestion"
GridLayout:
cols: 1
size_hint_y: 1
GridLayout:
cols: 1
NeuLabelinBox:
text: "Here the Question"
GridLayout:
cols: 1
size_hint_y: 0.1
UnteresMenue:
Please notice "UnteresMenue" which refer another Class in the kv language. I think I somehow mixed 2 Screens together in one. The kv code of "UnteresMenue"
<UnteresMenue>:
name: "UnteresMenue"
#id: UnteresMenue
GridLayout:
cols: 1
NeuButton:
text: root.labeltext
Now for the python part:
class UnteresMenue(Screen):
labeltext = StringProperty("Answer")
That works fine. But now I want to change the text of the label in this "UnteresMenue", when I press a certain button at the beginning of the app (Start Questions). The label in the "Untermenue" should change to a certain text. So to do this:
text: "Exam"
self.manager.get_screen('UnteresMenue').labeltext = text
For all other classes this method works fine. But not for that certain class "UnteresMenue". Is it because it is implemented in the question and therefor kv does not recognize its properties?
For any small hints I would be more than grateful!
Here an "Mini" Example:
In the Main Menu you get to the "Exam" Section (Press Here in the example). While entering this Section (Prüfungsmodus) the property of the questions should change. "Press Here" again to get to the questions.
Normally it says in the Top of the questions "This should change" And THIS is supposed to change the label into "Zeit" while entering the Prüfungsmodus Screen (Class def on_enter, in the python file), but it doesn't...
Python File:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen, TransitionBase
from kivy.properties import ObjectProperty, NumericProperty
from kivy.uix.popup import Popup
from kivy.uix.label import Label
from kivy.core.text import LabelBase
from kivy.core.window import Window
from kivy.graphics import Color, InstructionGroup, Line, Rectangle
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.properties import ListProperty
from kivy.uix.textinput import TextInput
from kivy.uix.checkbox import CheckBox
from kivy.uix.widget import Widget
from kivy.config import Config
from kivy.properties import StringProperty
from kivy.clock import Clock
from functools import partial
from kivy.uix.image import Image
from kivy.garden.navigationdrawer import NavigationDrawer as ND
from kivy.uix.scatter import Scatter
import random
import time
Window.clearcolor = (0.2,0.2, 0.2,1)
Window.size = (480, 800)
#--------------------------------- Hauptmenü -------------------------------------------
class hauptmenue(Screen, Widget):
pass
class Pruefungsmodus(Screen):
labeltext2 = StringProperty("hi")
def on_enter(self):
text = "Zeit"
self.manager.get_screen('OberesMenue').labeltext = text #DAS Klappt nicht
def StartPruefung(self):
sm.current = "ersteFrage"
class UnteresMenue(Screen):
background_color_Kappa = ListProperty([0.2,0.2,0.2, 1])
class OberesMenue(Screen):
BildLabeltext = StringProperty("Bilder\Loesung_Bild_pressed.png")
BildLabeltext2 = StringProperty("Bilder\Loesung_Bild.png")
labeltext = StringProperty("This should change")
class ersteFrage(Screen):
pass
class WindowManager(ScreenManager):
pass
kv = Builder.load_file("my.kv")
sm = WindowManager()
sm.add_widget(hauptmenue(name="hauptmenue"))
sm.add_widget(Pruefungsmodus(name="Pruefungsmodus"))
sm.add_widget(OberesMenue(name="OberesMenue"))
sm.add_widget(UnteresMenue(name="UnteresMenue"))
sm.add_widget(ersteFrage(name="ersteFrage"))
sm.current = "hauptmenue"
class Vorbrereitung(App):
pruefung = ObjectProperty(None)
def build(self):
return sm
if __name__ == "__main__":
Vorbrereitung().run()
my.kv file :
#:include alleFragen.kv
<NeuLabel2#Label>:
halign: "center"
color:1,1,1,1 # <-----------
canvas.before:
Color:
rgba: 0.2,0.2, 0.2,1
Rectangle:
pos: self.pos
size: self.size
<NeuLabelinBox#Label>:
font_size: "22sp"
color:0,0,0,1 # <-----------
canvas.before:
Color:
rgba: 0.949019608, 0.949019608, 0.949019608, 1
Rectangle:
pos: self.pos
size: self.size
<NeuCheckBox#CheckBox>:
color: 0, 0, 0, 1
canvas.before:
Color:
rgba: 0.949019608, 0.949019608, 0.949019608, 1
Rectangle:
pos: self.pos
size: self.size
<NeuButton#Button>:
font_size: "22sp"
background_normal: ''
#background_normal: "background.png"
background_color: 0.92549,0.92549,0.92549, 1
color:0,0,0,1 # <-----------
canvas.before:
Color:
rgba: 0.2,0.2, 0.2,1
Rectangle:
pos: self.pos
size: self.size
<NeuButtonKappa#Button>:
font_size: "40sp"
background_normal: ''
background_color: 0.2,0.2,0.2, 1
color:1,1,1,1 # <-----------
canvas.before:
Color:
rgba: 0.2,0.2, 0.2,1
Rectangle:
pos: self.pos
size: self.size
#---------------------------------- Hauptmenue ---------------------------------------------------------------------------------
<hauptmenue>:
name: "Hauptmenue"
GridLayout:
cols:1
#spacing: 20
GridLayout:
cols:1
padding: 20
size_hint_y: 0.2
NeuLabel2:
size_hint_x: 0.6
text: ""
font_size: (root.width**2 + root.height**2) / 13**4
halign: 'center'
valign: 'middle'
GridLayout:
cols:2
padding: 30
spacing: 20
size_hint_y: 0.5
BoxLayout:
NeuButton:
text: ''
BoxLayout:
NeuButton:
text: 'PRESS HERE'
on_release:
app.root.current = "Pruefungsmodus"
BoxLayout:
NeuButton:
text: ""
halign: 'center'
valign: 'middle'
BoxLayout:
NeuButton:
text: ""
BoxLayout:
padding: 10
size_hint_y: 0.15
NeuButton:
text: ''
#---------------------------------- Pruefungsmodus ---------------------------------------------------------------------------------
<Pruefungsmodus>:
name: "Pruefungsmodus"
#background_color: 1, 1, 1, 1
id: pruefungsmudos
GridLayout:
cols:1
#spacing: 20
GridLayout:
cols:3
padding: 20
size_hint_y: 0.2
Image:
size_hint_x: 0.2
source:"Bilder\Logo.png"
NeuLabel2:
size_hint_x: 0.6
text: 'Pr\u00FCfungs\nmodus'
font_size: (root.width**2 + root.height**2) / 12**4
halign: 'center'
valign: 'middle'
Image:
size_hint_x: 0.2
source:"Bilder\Logo2.png"
GridLayout:
cols:1
padding: 30
spacing: 10
size_hint_y: 0.4
NeuLabelinBox:
id: text2
text: root.labeltext2
color: 0,0,0,1 # <-----------
canvas.before:
Color:
rgba: 0.949019608, 0.949019608, 0.949019608, 1
Rectangle:
pos: self.pos
size: self.size
GridLayout:
cols:2
padding: 30
size_hint_y: 0.2
BoxLayout:
padding: 30
spacing: 10
NeuButton:
size_hint_x: 0.5
text: "Press Here"
on_release:
app.root.current = "ersteFrage"
NeuButton:
size_hint_x: 0.5
text: ""
on_release:
app.root.current = "hauptmenue"
#---------------------------------- Erste Frage ---------------------------------------------------------------------------------
<ersteFrage>:
name: "ersteFrage"
GridLayout:
cols: 1
size_hint_y: 1
GridLayout:
cols: 1
size_hint_y: 0.08
OberesMenue:
GridLayout:
cols: 1
size_hint_y: 0.1
NeuLabel2:
font_size: "18sp"
text: "Wie lautet......."
GridLayout:
cols: 1
size_hint_y: 0.7
padding: 20
background_color: 0.92549,0.92549,0.92549, 1
rows: 2
BoxLayout:
orientation:'horizontal'
NeuLabelinBox:
text: "h+u=ZU"
NeuCheckBox:
NeuLabelinBox:
text: "h+u=ZU"
NeuCheckBox:
BoxLayout:
orientation:'horizontal'
NeuLabelinBox:
text: "h+u=ZU"
NeuCheckBox:
NeuLabelinBox:
text: "h+u=ZU"
NeuCheckBox:
GridLayout:
cols: 1
size_hint_y: 0.1
UnteresMenue:
and the outsourced Top and Button Menu:
alleFragen.kv
<OberesMenue>:
id: OberesMenueee
name: "OberesMenue"
GridLayout:
cols:1
GridLayout:
#size_hint_y: 0.05
spacing: 20
cols: 3
NeuButton:
text: ""
size_hint_x: 0.16
background_color: 1,1,1, 1
background_down: root.BildLabeltext
background_normal: root.BildLabeltext2
color:1,1,1,1 # <-----------
canvas.before:
Color:
rgba: 0.2,0.2, 0.2,1
Rectangle:
pos: self.pos
size: self.size
NeuLabel2:
size_hint_x: 0.8
text: root.labeltext
NeuButtonKappa:
size_hint_x: 0.1
text: "MENU"
background_down: "Bilder\HintergurndFarbe_app.png"
on_release:
app.root.current = "hauptmenue"
<UnteresMenue>:
name: "UnteresMenue"
id: UnteresMenuee
GridLayout:
cols: 5
spacing: 20
padding: 20
NeuButton:
text: "<=="
NeuButton:
text: "<"
NeuButtonKappa:
text: 'k'
#background_color: root.background_color_Kappa
background_down: "Bilder\HintergurndFarbe_app.png"
NeuButton:
text: ">"
NeuButton:
text: "==>"
The problem is that you have two different instances of the OberesMenue Screen.
There is one created in your python:
sm.add_widget(OberesMenue(name="OberesMenue"))
And you have another created in your kv:
<ersteFrage>:
name: "ersteFrage"
GridLayout:
cols: 1
size_hint_y: 1
GridLayout:
cols: 1
size_hint_y: 0.08
OberesMenue:
In order to acces the second instance of OberesMenue, you can add an id:
<ersteFrage>:
name: "ersteFrage"
GridLayout:
cols: 1
size_hint_y: 1
GridLayout:
cols: 1
size_hint_y: 0.08
OberesMenue:
id: in_ersteFrage
Then in your on_enter() method of Pruefungsmodus, you can change that instance by using:
def on_enter(self):
text = "Zeit"
self.manager.get_screen('ersteFrage').ids.in_ersteFrage.labeltext = text #DAS Klappt nicht
Note that this changes the Label in the second instance of OberesMenue, but has no effect on the first. Your original code was changing the first instance, but not the second. And you can't put the same instance in both places at the same time, since a Widget can have only one parent at a time.
So, if those instances are intended to be identical, then you need to change the Label in both.
If you really want to share the same instance, you can keep your own record of where it is and use remove_widget() and add_widget() to move it from one parent to another.

KivyMD 0.103.0 causing errors with 'NavigationDrawerSubheader'

I recently updated kivyMD from 0.102.1 to 0.103.0 and i'm getting the following error:
raise FactoryException('Unknown class <%s>' % name)
kivy.factory.FactoryException: Unknown class
But when go back to version 0.102.1 everything works just fine. I'll post the code below but I just wanted to know if I wanted to update to 0.103.0 what do I need to change? I've tried to do some research but unable to find something that will fix the problem.
.py
#imported from kivy framework
from kivy.app import App
from kivymd.app import MDApp
from kivy.app import App
from datetime import datetime
from datetime import timedelta
from kivy.clock import Clock
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.image import Image
import weatherGrab
from weatherGrab import weatherCheck
import os
#1st screen
class Login_Screen(Screen):
#Takes user input from the .KV file, converts it to string and verifies if its a saved login
def verify_credentials(self):
Username = self.ids.Username_userInput
Password = self.ids.Password_userInput
Username_string = Username.text
Password_string = Password.text
#Allows the variable to be used in another class and method
Login_Screen.verify_credentials.GGG = Username.text
#checks if user input is equal to temp database
if self.ids["Username_userInput"].text == "Username" and self.ids["Password_userInput"].text == "Password":
self.manager.current = "Homepage_Screen"
print("USER LOGIN DATA: " + Username_string +" "+Password_string)
weatherGrab.weatherCheck()
#print('CURRENT WEATHER - London','\n',weatherCheck.currentWeather,'\n' ,weatherCheck.temp)
#print('HERE',var1)
#x = dir(platform) prints all function from that lib
#after log in, sets user input to empty so the next user can login
def clean(self):
self.ids["Username_userInput"].text = ""
self.ids["Password_userInput"].text = ""
#saving user inputs to a text file (temp database)
def save_data(self):
Username = self.ids.Username_userInput
Password = self.ids.Password_userInput
Username_string = Username.text
Password_string = Password.text
TextDoc = open("UserLogin.txt", "a")
username = Username_string
password = Password_string
if username == '' and password == '':
pass
else:
TextDoc.write("\n"+username+","+password)
TextDoc.close()
#loads data from the file (debugging/testing)
def load_data(self):
f = open("UserLogin.txt", "r")
print("FROM TEXT FILE:"+ f.read())
#2nd screen
class Homepage_Screen(Screen):
#Event dispatcher to load data when user enters the second screen
def on_enter(self):
self.load_info()
self.weather()
def weather(self):
self.ids["temp"].text = weatherCheck.temp
self.ids["date"].text = weatherCheck.currentDate
#Text prints in termial for testing/debugging
def load_info(self):
print("PASSING USERNAME TO HOMEPAGE: "+Login_Screen.verify_credentials.GGG)
self.ids["USERNAME"].text = "Welcome"+" "+Login_Screen.verify_credentials.GGG
#Saves User input from the notes textinput
def save_notes(self):
UserNotes = self.ids.UserInput_notes
UserNote = UserNotes.text
TextDoc = open("UserLogin.txt", "a")
TextDoc.write("," + UserNote)
TextDoc.close()
#3rd screen
class Application_Screen(Screen):
pass
#4th screen
class Logout_Screen(Screen):
def newline(self):
TextDoc = open("UserLogin.txt", "a")
TextDoc.write("\n")
TextDoc.close()
def forcequit(self):
exit()
#class for all screens
class ScreenManagement(ScreenManager):
pass
class MainApp(MDApp):
def build(self):
#declaring time from python, and making it refresh every second
self.now = datetime.now()
Clock.schedule_interval(self.update_clock, 1)
def update_clock(self, *args):
self.now = self.now + timedelta(seconds=1)
#Allows for time to be shown on all screens
self.root.get_screen("Homepage_Screen").ids["CurrentTime"].text = self.now.strftime("%H:%M:%S")
self.root.get_screen("Logout_Screen").ids["CurrentTime"].text = self.now.strftime("%H:%M:%S")
self.root.get_screen("Login_Screen").ids["CurrentTime"].text = self.now.strftime("%H:%M:%S")
#print(self.now.strftime("%H:%M:%S"))
MainApp().run()
.kv
#:kivy 1.0
#:import hex kivy.utils.get_color_from_hex
#styles that will apply to all intences for each tag
<MDRaisedButton>:
font_size:18
<Label>:
color: 0,0,0,1
#declaring screen managers and printing them in this order
ScreenManagement:
Login_Screen:
name:"Login_Screen"
id: woow
Homepage_Screen:
name:"Homepage_Screen"
Application_Screen:
name:"Application_Screen"
Logout_Screen:
name:"Logout_Screen"
#style for login screen
<Login_Screen>:
#background color
FloatLayout:
spacing: 10
canvas.before:
Color:
rgba: hex('#eff3fa')
Rectangle:
size: self.size
pos: self.pos
#Navbar
MDToolbar:
id: fb
pos_hint: {'center_x': 0.5, 'top':1.0}
size_hint_y:None
height: 50
title: "Virtual Assistant"
md_bg_color: hex('#132843')
Label:
id: CurrentTime
font_size:18
size_hint_x: .1
color: (1,1,1,1)
#login container
#background color/positioning
BoxLayout:
spacing: 10
orientation: 'vertical'
padding: 50
canvas.before:
Color:
rgba: hex('#000')
Rectangle:
size: self.size
pos: self.pos
pos_hint: {'center_x': 0.5, 'center_y': 0.5}
size_hint: 0.33, None
size_hint_min_x: 200
height: self.minimum_height
#LOGIN CONTENT
#logo
Image:
source: 'Logo.png'
size_hint: None, None
size: 100, 100
pos_hint: {'center_x': 0.5, 'center_y': 0.0}
MDTextField:
id: Username_userInput
hint_text:"Username"
text:"Username"
line_color_normal: 0,0,0,1
MDTextField:
id: Password_userInput
hint_text:"Password"
text:"Password"
password: True
line_color_normal: 0,0,0,1
#color_mode:'accent'
Button:
text:"Login"
size_hint_y: None
height: 60
padding: 10,10
background_color: (2.08, 2.40, 1.92,1)
size_hint: 0.40, None
pos_hint: {'center_x': 0.5, 'center_y': 0.0}
on_press: root.verify_credentials() , root.save_data(), root.clean(), root.load_data()
#style for Homepage screen
<Homepage_Screen>:
#SIDEBAR BUTTONS
NavigationLayout:
id: nav_layout
MDNavigationDrawer:
drawer_logo:'Logo.png'
NavigationDrawerSubheader:
id: USERNAME
NavigationDrawerIconButton:
icon:"home"
text:"Homepage"
theme_text_color: 'Custom'
on_release:
screen_manager.current = "Homepage"
NavigationDrawerIconButton:
icon:'application'
text: "Application"
on_release:
screen_manager.current = "Application"
NavigationDrawerIconButton:
icon: 'dictionary'
text: "Dictionary"
on_release:
screen_manager.current = "Dictionary"
MDRectangleFlatIconButton:
icon:'logout'
text: "Logout"
#on_press: root.clean()
on_release: app.root.current = "Logout_Screen"
size_hint: 1, None
font_size:20
text_color: 0,0,0,1
#BACKGROUND
FloatLayout:
spacing: 10
canvas.before:
Color:
rgba: hex('#eff3fa')
Rectangle:
size: self.size
pos: self.pos
#NAVBAR
MDToolbar:
id: fb
pos_hint: {'center_x': 0.5, 'top':1.0}
size_hint_y:None
height: 50
title: "Virtual Assistant"
md_bg_color: hex('#132843')
left_action_items: [['menu', lambda x: root.ids.nav_layout.toggle_nav_drawer()]]
Label:
id: CurrentTime
size_hint_x: .1
font_size:18
color: (1,1,1,1)
#SIDEBAR SCREEN STYLE
ScreenManager:
id: screen_manager
#HOMEPAGE SCREEN STYLE
Screen:
name: "Homepage"
BoxLayout:
spacing: 10
orientation: 'vertical'
padding: 10
canvas.before:
Color:
rgba: (1,1,1,.8)
Rectangle:
size: self.size
pos: self.pos
pos_hint: {'center_x': 0.5, 'top': (root.height - fb.height)/root.height}
size_hint: 0.3, None
height: 35
GridLayout:
rows: 3
cols: 3
padding: 10
spacing: 15
#pos_hint: {"center_x":0.6, "center_y":0.0}
Label:
id:date
color: (0,0,0,1)
size_hint_x: 2
Label:
id:temp
color: (0,0,0,1)
size_hint_x: 2
Label:
text:'icon'
color: (0,0,0,1)
size_hint_x: 2
BoxLayout:
orientation: 'horizontal'
spacing: 10
padding: 10
canvas.before:
Color:
rgba: (1,1,1,1)
Rectangle:
size: self.size
pos: self.pos
size_hint: 0.8, None
height: 60
pos_hint: {'center_x': .5, 'center_y':.5}
TextInput:
height:60
size_hint: 5, None
focus: True
multiline: False
font_size: 25
padding_y:15
background_color: 1,1,1,0
foreground_color: 0,0,0,1
pos_hint:{'center_x':0, 'center_y':0.5}
MDRectangleFlatIconButton:
icon:'search-web'
height:45
text_color: 0,0,0,1
md_bg_color: hex("#D0F0C0")
pos_hint: {'center_x': 0.5, 'center_y': 0.5}
Label:
text:'Search'
font_size:18

Kivy Buttons and Labels size based on display size

I'm trying to figure out how to make my buttons and labels fix perfectly depending on my display size. So if the phone display is different, it will always be in fixed size.
Python Code:
import kivy
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
class OpeningScreen(Screen):
pass
class LoginScreen(Screen):
pass
class SignupScreen(Screen):
pass
class ScreenManagement(ScreenManager):
pass
AppKv = Builder.load_file("App.kv")
class MyApp(App):
def build(self):
return AppKv
if __name__ == '__main__':
MyApp().run()
Kv code:
#: import FadeTransition kivy.uix.screenmanager.FadeTransition
#: import hex kivy.utils.get_color_from_hex
#------------------------------------------------------------#
ScreenManagement:
transition: FadeTransition()
OpeningScreen:
LoginScreen:
SignupScreen:
#------------------------------------------------------------#
<OpeningScreen>:
name: "OpeningScreen"
canvas:
Color:
rgb: 1, 1, 1
Rectangle:
pos: self.pos
size: self.size
Label:
text: "Welcome"
color: 1,1,1,1
font_size: 45
size_hint: 0.2,0.1
pos_hint: {"x":0.40, "top":0.995}
Button:
size: 100,75
on_release: app.root.current = "LoginScreen"
text: "Login"
font_size: 50
color: 1,1,1,1
background_color: (0,0,0,1)
background_normal: ""
background_down: ""
size_hint: 0.3,0.2
pos_hint: {"x":0.35, "top":0.7}
Button:
size: 100,75
on_release: app.root.current = "SignupScreen"
text: "Sign up"
font_size: 50
color: 1,1,1,1
background_color: (0,0,0,1)
background_normal: ""
background_down: ""
size_hint: 0.3,0.2
pos_hint: {"x":0.35, "top":0.4}
#------------------------------------------------------------#
<LoginScreen>:
name: "LoginScreen"
canvas:
Color:
rgb: 1, 1, 1
Rectangle:
pos: self.pos
size: self.size
Label:
text: "Login In"
color: 0,0,0,1
font_size: 45
size_hint: 0.2,0.1
pos_hint: {"x":0.40, "top":0.995}
#------------------------------------------------------------#
<SignupScreen>:
name: "SignupScreen"
canvas:
Color:
rgb: 1, 1, 1
Rectangle:
pos: self.pos
size: self.size
Label:
text: "Sign Up"
color: 0,0,0,1
font_size: 45
size_hint: 0.2,0.1
pos_hint: {"x":0.40, "top":0.995}
I would really appreciate if anyone could help me with this. I was trying to find out how to do this but I couldn't
Button and Label sizes can be set using several different approaches:
Use Kivy Metrics. You can set sizes using dp (for example dp(100)), this is a Density-independent Pixel size. There is also a sp (used similarly) that is Scale-independent Pixels (normally used for font sizes)
Use self.texture_size. You can set sizes using this as size: self.texture_size. This will make your Button and Label widgets just large enough to fit the text in it. You can add some padding by using something like:
width: self.texture_size[0] + dp(10)
height: self.texture_size[1] + dp(10)
Use size_hint. This will ensure that the Button and Label widgets take up the same percentage of your display, regardless of the device.
Don't forget to set size_hint to None, None for the first two above to work.

KIVY: adding buttons in a sub layout when a button is pressed (on_release)

The screen has multiple layouts all child of a box layout. I am trying to add a button in the last sub layout (grid-layout) when a button in other layout is clicked. The code does not crash but nothing happens too. I want to add buttons to the layout with id drinkslayout when a button is clicked eg pepsi,sprite
Python:
class MainScreen(Screen):
pass
class AnotherScreen(Screen):
pass
class ScreenManagement(ScreenManager):
pass
class Stacks(StackLayout):
pass
present=Builder.load_file('hellokivy2.kv') #Specifying location of kv file
class MainApp(App):
def build(self):
return present
def drinksSelect(self,value): #creating a button by referring the id of the layout in which to create button
print(value)
yolo = AnotherScreen()
yolo2 = yolo.ids.newButtonLayout
button = Button(text="value",size_hint= (0.2,0.4))
yolo2.add_widget(button)
if __name__ == "__main__":
MainApp().run()
KV
#: import FadeTransition kivy.uix.screenmanager.FadeTransition
ScreenManagement:
transition: FadeTransition()
MainScreen:
AnotherScreen:
<MainScreen>:
name: "main"
canvas.before:
Color:
rgba: 1, 1, 1, 1
Rectangle:
pos: self.pos
size: self.size
BoxLayout:
orientation: 'vertical'
size:root.size
Button:
text: "Slideshow"
GridLayout:
cols: 2
Button:
text: "Burger"
Button:
text: "Drinks"
on_release: app.root.current = "other"
Button:
text: "Fries"
Button:
text: "Others"
Label:
text: "Your Cart"
font_size: 40
color:(0,0,0,1)
size_hint_y: None
canvas.before:
Color:
rgba:150,10,200,0.5
Rectangle:
pos: self.pos
size: self.size
<AnotherScreen>:
name: "other"
canvas.before:
Color:
rgba: 1, 1, 1, 1
Rectangle:
pos: self.pos
size: self.size
BoxLayout:
size:root.size
orientation: 'vertical'
GridLayout:
size_hint_y:0.1
orientation: 'vertical'
rows: 1
Button:
color: 1,1,1,1
font_size: 25
size_hint_y:0.1
text: "Back Home"
on_release: app.root.current = "main"
Label:
text: "Project BAM"
canvas.before:
Color:
rgba: 0,0,0,1
Rectangle:
pos: self.pos
size: self.size
Button:
color: 1,1,1,1
font_size: 25
size_hint_y:0.1
text: "Profile"
on_release: app.root.current = "main"
Button:
color: 1,1,1,1
font_size: 25
size_hint_y:0.9
text: "Whats New"
on_release: app.root.current = "main"
GridLayout:
rows: 2
Button:
text: "Pepsi"
on_release: app.drinksSelect(1)
Button:
text: "7up"
on_release: app.drinksSelect(2)
Button:
text: "Fanta"
on_release: app.drinksSelect(3)
Button:
text: "Mountain Dew"
on_release: app.drinksSelect(4)
Button:
text: "Diet Pepsi"
on_release: app.drinksSelect(5)
Button:
text: "Sprite"
on_release: app.drinksSelect(6)
GridLayout:
id: drinksLayout
size_hint_y: 0.3
orientation: 'horizontal'
rows: 1
Button:
id: label1
size_hint: 0.2,0.4
background_normal:'1.jpg'
text: 'B1'
Button:
id: label2
size_hint: 0.2,0.4
background_normal:'1.jpg'
text: 'B1'
Button:
id: label3
size_hint: 0.2,0.4
background_normal:'1.jpg'
text: 'B1'
Ok the problem was your drinksSelect method, also you need to keep the value of your screens
Try this:
py:
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang.builder import Builder
from kivy.uix.stacklayout import StackLayout
from kivy.uix.button import Button
from kivy.properties import ObjectProperty
class MainScreen(Screen):
pass
class AnotherScreen(Screen):
dl = ObjectProperty()
l = 0
limit = 3 # Fix your limit here 3 is an example
class ScreenManagement(ScreenManager):
m_s = ObjectProperty() # Here I will keep the value of the MainScreen
a_s = ObjectProperty() # Here the AnotherScreen so I can use them later
class Stacks(StackLayout):
pass
present = Builder.load_file('hellokivy2.kv') # Specifying location of kv file
class MainApp(App):
def build(self):
return present
def drinksSelect(self,value): # creating a button by referring the id of the layout in which to create button
print(value)
if self.root.a_s.l < self.root.a_s.limit: # You know what I mean
button = Button(text=str(value), size_hint= (0.2,0.4))
self.root.a_s.ids['place_remaining'].add_widget(button)
self.root.a_s.l += 1
if __name__ == "__main__":
MainApp().run()
kv:
#: import FadeTransition kivy.uix.screenmanager.FadeTransition
ScreenManagement:
m_s: m_s # so I can use it in the .py file
a_s:a_s # same here
transition: FadeTransition()
MainScreen:
id: m_s
AnotherScreen:
id: a_s
<MainScreen>:
name: "main"
canvas.before:
Color:
rgba: 1, 1, 1, 1
Rectangle:
pos: self.pos
size: self.size
BoxLayout:
orientation: 'vertical'
size:root.size
Button:
text: "Slideshow"
GridLayout:
cols: 2
Button:
text: "Burger"
Button:
text: "Drinks"
on_release: app.root.current = "other"
Button:
text: "Fries"
Button:
text: "Others"
Label:
text: "Your Cart"
font_size: 40
color:(0,0,0,1)
size_hint_y: None
canvas.before:
Color:
rgba:150,10,200,0.5
Rectangle:
pos: self.pos
size: self.size
<AnotherScreen>:
name: "other"
dl : drinksLayout
canvas.before:
Color:
rgba: 1, 1, 1, 1
Rectangle:
pos: self.pos
size: self.size
BoxLayout:
size:root.size
orientation: 'vertical'
GridLayout:
size_hint_y:0.1
orientation: 'vertical'
rows: 1
Button:
color: 1,1,1,1
font_size: 25
size_hint_y:0.1
text: "Back Home"
on_release: app.root.current = "main"
Label:
text: "Project BAM"
canvas.before:
Color:
rgba: 0,0,0,1
Rectangle:
pos: self.pos
size: self.size
Button:
color: 1,1,1,1
font_size: 25
size_hint_y:0.1
text: "Profile"
on_release: app.root.current = "main"
Button:
color: 1,1,1,1
font_size: 25
size_hint_y:0.9
text: "Whats New"
on_release: app.root.current = "main"
GridLayout:
rows: 2
Button:
text: "Pepsi"
on_release: app.drinksSelect(1)
Button:
text: "7up"
on_release: app.drinksSelect(2)
Button:
text: "Fanta"
on_release: app.drinksSelect(3)
Button:
text: "Mountain Dew"
on_release: app.drinksSelect(4)
Button:
text: "Diet Pepsi"
on_release: app.drinksSelect(5)
Button:
text: "Sprite"
on_release: app.drinksSelect(6)
GridLayout:
id: drinksLayout
size_hint_y: 0.3
orientation: 'horizontal'
rows: 1
GridLayout:
id: place_remaining
rows: 1
size_hint_x: 80
Button:
id: label1
width: 40 # Set the size_hint_x to None and then set the width if you want a fixed dimension
size_hint: None,0.4
background_normal:'1.jpg'
text: 'B1'
Button:
id: label2
width: 40
size_hint: None,0.4
background_normal:'1.jpg'
text: 'B1'
Button:
id: label3
width: 40
size_hint: None,0.4
background_normal:'1.jpg'
text: 'B1'
Outputs:
I hope that the code is a bit clear now

Categories