how can i create a table in python kivy - python

I'm writing a python program to compute few values in two textinput, but The Result should be in a table ... I created it as a label but it doesn't practical.
how can i create a table !
Thank you very much
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.properties import ObjectProperty, StringProperty
from kivy.uix.textinput import TextInput
from kivy.app import App
from kivy.core.window import Window
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.clock import Clock
Window.clearcolor = (0.5, 0.5, 0.5, 1)
class WindowManager(ScreenManager):
pass
class BestWindow(Screen):
my_result = StringProperty("")
inpt_one = ObjectProperty(None)
result_layout = ObjectProperty(None)
result_layout1 = ObjectProperty(None)
result_layout2 = ObjectProperty(None)
result_layout5 = ObjectProperty(None)
test3 = ObjectProperty(None)
def __init__(self, **kwargs):
super(BestWindow, self).__init__(**kwargs)
Window.bind(on_key_down=self._on_keyboard_down)
def _on_keyboard_down(self, instance, keyboard, keycode, text, modifiers):
if self.test3.focus and keyboard== 13: # 32 - Cpace key presssed Ascii
self.calculate()
def calculate(self):
self.result_layout.clear_widgets()
self.result_layout1.clear_widgets()
nums_one = self.inpt_one.text.strip().split(" ")
nums_two = self.inpt_two.text.strip().split(" ")
if(len(nums_one) < len(nums_two)):
for _ in range(len(nums_two)-len(nums_one)):
nums_one.append(0)
elif(len(nums_two) < len(nums_one)):
for _ in range(len(nums_one)-len(nums_two)):
nums_two.append(0)
result = [(int(x) + int(y)) for x,y in zip(nums_one, nums_two) ]
aList = []
for f in range(len(nums_one)):
aList.append(f)
self.ids.result_layout5.add_widget(Label(text='Num: {} '.format(f)))
bList = []
for i in range(len(nums_one)):
self.ids.result_layout1.add_widget(Label(text='1.Gas: %{} '.format(nums_one[i])))
bList.append(i)
cList = []
for j in range(len(nums_two)):
bList.append(j)
self.ids.result_layout2.add_widget(Label(text='2.Gas: %{} '.format(nums_two[j])))
dList = []
for res in result:
res = int(res)
dList.append(res)
self.ids.result_layout.add_widget(Label(text='Sum: %{} '.format(res)))
self.inpt_one.text = ''
self.inpt_two.text = ''
kv = Builder.load_file("MyMain.kv")
class TestApp(App):
def build(self):
b1 = WindowManager()
return b1
if __name__ == "__main__":
TestApp().run()
the user should enter the first value in the first box and then space then the second value and so on.
then he presses enter .. and can then continue first value in second box space then the second value.
MyMain.kv file
<CustButton#Button>:
font_size: 40
<WindowManager>:
BestWindow:
<BestWindow>:
name: "erst"
inpt_one: inpt_one
inpt_two: inpt_two
result_layout: result_layout
result_layout1:result_layout1
result_layout2:result_layout2
result_layout5:result_layout5
test3: test3
GridLayout:
spacing: 10
cols:1
Label:
text: "das Gas 1"
background_color: 1, 0, 0, 1
TextInput:
id:inpt_one
focus : True
text: ' '
width: 100
multiline: False
on_text_validate: inpt_two.focus = True
Label:
text: "das Gas 2"
background_color: 1, 0, 0, 1
TextInput:
id:inpt_two
focus : True
text: ' '
width: 100
multiline: False
on_text_validate:
test3.background_normal = ''
test3.background_color = [0, 0, 1, 0.5] # 50% translucent blue
test3.focus = True
Button:
id : test3
focus: False
text: "Table!"
on_press:
root.calculate()
BoxLayout:
orientation: "horizontal"
BoxLayout:
id: result_layout5
orientation: "horizontal"
BoxLayout:
orientation: "horizontal"
BoxLayout:
id: result_layout1
orientation: "horizontal"
BoxLayout:
orientation: "horizontal"
BoxLayout:
id: result_layout2
orientation: "horizontal"
BoxLayout:
orientation: "horizontal"
BoxLayout:
id: result_layout
orientation: "horizontal"

Yes tables are a bit clunky. Although I'm not sure if you need all those box layouts, isn't the grid layout sufficient? But otherwise, a quick and easy table can be made on a single Label widget with formatted strings and a mono-spaced font, because Label does process \n for new line. The only awkwardness is that Label doesn't likewise support \t for tab spacing between the columns, so the \t escapes have to be rendered in advance in python. This can be done with expandtabs string method.
Label(text='l1c1\tl1c2\nll2c1\tll2c2'.expandtabs(8),font_name='UbuntuMono-R')

Related

How to pass an instance of a Button in Kivy Builder

I would like to pass the instance of a button when clicked, to obtain its information - more importantly the text information. For now I have one screen with a list of songs as buttons. When clicked, I would like to open a text file with the name of the button and display its contents in a new screen. However, I don't know how to get the button that was pressed on the new screen. Any help is appreciated.
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen, SlideTransition
from kivy.lang import Builder
import os
def get_song_list():
songs = [x for x in os.listdir("../data/") if ".txt" in x]
string = ""
for song in songs:
name = song.replace("_", " ").replace(".txt", "")
string += f"""Button:
text: "{name}"
background_color: 0, 0, 0, 0
size_hint: 0.5, None
height: 40
on_press:
root.manager.transition.direction = 'left'
root.manager.current = 'midi_sheet'\n\t\t\t"""
return string
def get_notes_in_song(song):
string = ""
with open(song) as f:
lines = f.readlines()
for line in lines:
string += line+"\n"
return string
class Home(Screen):
pass
class MidiSheet(Screen):
pass
Builder.load_string(f"""
<Home>:
ScrollView:
size_hint: 1, None
size: root.width, root.height
GridLayout:
cols: 1
spacing: 10
size_hint_y: None
{get_song_list()}
<MidiSheet>
ScrollView:
size_hint: 1, None
size: root.width, root.height
GridLayout:
cols: 1
spacing: 10
size_hint_y: None
Button:
text: "Back"
on_press:
root.manager.transition.direction = 'right'
root.manager.current = 'home'
Label:
text: "You opened "
""")
sm = ScreenManager(transition=SlideTransition())
sm.add_widget(Home(name="home"))
sm.add_widget(MidiSheet(name="midi_sheet"))
class Localiser(App):
def build(self):
return sm

Kivy - ScreenManager saying it does not recognize another screen name despite it being there?

So, I wanted to create an app that created tasks/habits in kivy. Basically, there would be a screen that shows you your tasks/habits, and you could click on a button to take you to another screen to create a new task/habit. You would input information about the task/habit in that screen, and click the submit button. The submit button would add the task/habit to the first screen. However, when I run my code, it works the first time. I can go to the second screen, add my habit/code and then go back to the first screen. However, when I click the button on the first screen, it gives me an error.
The error being: kivy.uix.screenmanager.ScreenManagerException: No Screen with name "second".
Here is my code:
main.py:
from kivy.lang import Builder
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.widget import Widget
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.image import Image
from PIL import Image
import numpy as np
class FirstWindow(Screen):
def add_label(self, name, time, date):
label = Label(text= f' {name}, {time}, {date}')
self.ids.boxlayout.add_widget(label)
class SecondWindow(Screen):
a_task = False
a_habit = False
name = ""
time = ""
date = ""
def task_button(self):
self.a_task = True
self.a_habit = False
def habit_button(self):
self.a_habit = True
self.a_task = False
def submit_button(self):
self.name = self.ids.the_name.text
self.time = f'{self.ids.time_spinner_1.text}:{self.ids.time_spinner_2.text}'
self.date = f'{self.ids.date_spinner_1.text}/{self.ids.date_spinner_2.text}'
def get_name(self):
return self.name
def get_time(self):
return self.time
def get_date(self):
return self.date
kv = Builder.load_file('Button.kv')
class ButtonApp(App):
def build(self):
sm = ScreenManager()
sm.add_widget(FirstWindow())
sm.add_widget(SecondWindow())
return sm
if __name__ == '__main__':
ButtonApp().run()
Button.kv:
<FirstWindow>:
name: "first"
BoxLayout:
id: boxlayout
orientation: "vertical"
canvas.before:
Color:
rgba: (0.3,0.33,0.3,1)
Rectangle:
pos: self.pos
size: self.size
FloatLayout:
Label:
text: "To Do List"
font_size: 32
pos_hint: { 'right': 0.65, 'top': 1.4 }
Button:
text: "add a task"
on_release: root.manager.current = "second"
<SecondWindow>:
name: "second"
BoxLayout:
orientation: "vertical"
spacing: "10dp"
canvas.before:
Color:
rgba: (0.3,0.33,0.3,1)
Rectangle:
pos: self.pos
size: self.size
FloatLayout:
Label:
text: "Add A Task"
font_size: 32
pos_hint: { 'right': 0.65, 'top': 1.2 }
BoxLayout:
orientation: "horizontal"
Button:
text: "task"
on_press: root.task_button()
Button:
text: "habit"
on_press: root.habit_button()
TextInput:
id: the_name
text: "Name"
Label:
text: "alert"
BoxLayout:
orientation: "horizontal"
Spinner:
id: time_spinner_1
text: "00"
values: ['1','2','3','4','5','6','7','8','9','10','11', '12']
Spinner:
id: time_spinner_2
text: "00"
values: ['01','02','03','04','05','06','07','08','09','10','11', '12', '13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','32','33','34','35','36','37','38','39','40','41','42','43','44','45','46','47','48','49','50','51','52','53','54','55','56','57','58','59']
BoxLayout:
orientation: "horizontal"
Spinner:
id: date_spinner_1
text: "00"
values: ['1','2','3','4','5','6','7','8','9','10','11', '12']
Spinner:
id: date_spinner_2
text: "00"
values: ['01','02','03','04','05','06','07','08','09','10','11', '12', '13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31']
Button:
text: "submit"
on_press: root.submit_button()
on_release:
root.manager.current = "first"
root.manager.get_screen("first").add_label(root.get_name(), root.get_time(), root.get_date())
Your code:
def submit_button(self):
self.name = self.ids.the_name.text
self.time = f'{self.ids.time_spinner_1.text}:{self.ids.time_spinner_2.text}'
self.date = f'{self.ids.date_spinner_1.text}/{self.ids.date_spinner_2.text}'
changes the name property of the SecondWindow Screen, so trying to change Screen to the second will no longer work. It looks like you are trying to use name for some other purpose. I suggest you use a variable with a different name.

How to create an buttonloop with parameter in kivy, after the GUI has generated?

I have an problem with the Kivy-Libaray. I' m currently writing the front end, for a ShoppinglistApp. I have an main menu, where you can select what you want to do(add List/ Shop) from where you can get to the Shop selection.
In the shop selection Menu are 4 Shops.
all Items(Produkt) are stored in a list.
If you select the Shop, then for each Item(from this Shop) a Button should be created.
I tired this solution:
from kivy.app import App
from kivy.metrics import dp
from kivy.lang import Builder
from kivy.properties import StringProperty
from kivy.uix.stacklayout import StackLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
# the rest
class Produkt:
def __init__(self, name, amount, market):
self.name = name
self.amount = amount
self.market = market
eklist = []
for i in range(0, 100):
nn = "Banane" + str(i)
eklist.append(Produkt(nn, 0, "Baumarkt"))
# Define Screens
class FirstWindow(Screen):
pass
class SecondWindow(Screen):
pass
class ThirdWindow(Screen):
pass
class WindowManager(ScreenManager):
pass
"""Anfang der Chose"""
class Box(BoxLayout):
pass
# Gvar is a class I created for the purpose of transporting variable(s). Especially the selected shop.
class Gvar:
def __init__(self, var1):
self.var1 = var1
def get(self):
return self.var1
gvar = Gvar("default")
# SetBox ist the Class for changing the variable through the shop selection menu.
class SetBox(BoxLayout):
def set(self, market):
gvar.var1 = market
print("Set")
print(gvar.var1)
class BLE(BoxLayout):
pass
# This is the Menus which makes Problems.
class SLE(StackLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
for p in eklist:
# In theory, this if request should always be triggerd. In praxis, I made the else Request to debug.
# for Text normally would appear p.name, but I changed it for debugging. Text shown(gvar.var1) is "default".
if p.market == str(gvar.get()):
b = Button(text=str(gvar.get()), size_hint=(None, None), color="blue", size=(dp(200), dp(100)),
on_press=lambda *args: self.test1(*args, str(p.name)))
b.prod = p
self.add_widget(b)
else:
b = Button(text=str(gvar.get()), size_hint=(None, None), color="green", size=(dp(200), dp(100)),
on_press=lambda *args: self.test1(*args, str(p.name)))
b.prod = p
self.add_widget(b)
market = None
# test 1 is a placeholder for a Backend funktion
# Here I print the Produkt and gvar.var1, to debug. Here it get for gvar.var1 the in the GUI selected Value.
def test1(self, b, i):
print("Initialize test2, please wait...")
print(b.prod.name, b.prod.amount, b.prod.market, gvar.var1)
"""Ende der Chose"""
kv = Builder.load_file('einkaufsliste.kv')
class EinkaufsApp(App):
def build(self):
return kv
if __name__ == '__main__':
EinkaufsApp().run()
+
Here is the Kivy file.
WindowManager:
FirstWindow:
SecondWindow:
ThirdWindow:
&ltFirstWindow&gt:
name: "first"
Box:
orientation: "vertical"
size :root.width, root.height
Label:
text: "Hauptmenü"
size_hint: 1, .2
font_size: 32
Button:
text: "Einkaufen"
font_size: 32
background_normal: ' '
background_color: "#666e00"
on_release:
app.root.current = "third"
root.manager.transition.direction = "left"
Button:
text: "Einkaufsliste updaten"
font_size: 32
background_normal: ' '
background_color: "#660000"
on_release:
app.root.current = "second"
root.manager.transition.direction = "left"
&ltSecondWindow&gt:
name: "second"
BLE:
id: BLE
orientation: "vertical"
Button:
text: "to first"
size_hint: 1, .1
font_size: 24
on_release:
app.root.current = "first"
root.manager.transition.direction = "right"
TextInput:
multiline: False
size_hint: 1, .1
SVE:
&ltThirdWindow&gt:
name: "third"
SetBox:
orientation: "vertical"
size :root.width, root.height
id:SetBox
Box:
orientation: "horizontal"
size_hint: 1, .4
Button:
text: "to first"
size_hint: .2, 1
font_size: 24
on_release:
app.root.current = "first"
root.manager.transition.direction = "right"
Label:
text: "Markt auswählen"
size_hint: .8, 1
font_size: 32
Button:
text: "Supermarkt"
font_size: 32
background_normal: ' '
background_color: "#a1b2e3"
on_release:
app.root.current = "second"
root.manager.transition.direction = "left"
on_press: SetBox.set("Supermarkt")
Button:
text: "Drogerie"
font_size: 32
background_normal: ' '
background_color: "#c7bbc9"
on_release:
app.root.current = "second"
root.manager.transition.direction = "left"
on_press: SetBox.set("Drogerie")
Button:
text: "Baumarkt"
font_size: 32
background_normal: ' '
background_color: "#b4eeb4"
on_release:
app.root.current = "second"
root.manager.transition.direction = "left"
on_press: SetBox.set("Baumarkt")
Button:
text: "Elektrogerätefachhandel"
font_size: 32
background_normal: ' '
background_color: "#f4c2c2"
on_release:
app.root.current = "second"
root.manager.transition.direction = "left"
on_press: SetBox.set("Elektrogerätefachhandel")
&ltSVE#ScrollView&gt:
SLE:
id: Scrollwin
size_hint: 1, None
height: self.minimum_height
&ltSLE&gt:
# orientation: "rl-bt"
# spacing: "1dp", "1dp"
</code></pre>
I think the Problem is, that kivy creates the whole GUI before I can change the variable.
Is there a way to reload the Screen or do I have to make for each market/shop another Screen?
It's possible to do what you want. You have to add the items to the corresponidng layout. I'll give you an example with a project I did some time ago:
class ExmapleApp(App):
def build(self):
#Create GridLayout where you will add and remove widgets
self.gridRooms = gridRooms = GridLayout(cols=10, padding=10, spacing=10,
row_force_default=True, row_default_height=50, size_hint_y=None)
gridRooms.bind(minimum_height=gridRooms.setter('height'))
# Generate 10 Rooms items
for i in range(10):
labl = NewLabel() #Instace of NewLabel
labl.num = str(i+1) #Number of room
labl.roomName = "Room "+str(labl.num) # Room name
labl.filename = '12916_sweet_trip_mm_kwik_mod_01.wav'
roomsList.append(labl) #This add the room to a list for further reference
gridRooms.add_widget(labl) #This add the rooms to a grid
Here's an image of how it looks so far:
Finally, you can add widgets to that GridLayout:
#Create the object you want to Add
labl = NewLabel() #Instace of NewLabel
labl.num = str(11) #Number of room
labl.roomName = "Room "+str(labl.num) # Room name
labl.filename = '12916_sweet_trip_mm_kwik_mod_01.wav'
roomsList.append(labl) #This add the room to a list for further reference
#This add the widgets 3 secs after the program starts
Clock.schedule_once(lambda x: gridRooms.add_widget(roomsList[10]), 3) #Add room 11
You can even have a callback to create a new widget everytime you press a button.
To remove a widget just:
gridRooms.remove_widget(roomsList[10]) #Removes Room 11

OCR using Kivy and Screenmanager issue passing variable between screens

I am building an OCR application for visually impaired users. I'm wanting the app to open straight away onto the camera screen, when the user takes a pic on button press I want ocr process to occur and display the output on the text screen in a lbl or txtbox and have a TTS read out what the text says. My issue is that i am having trouble obtaining the output of ocr and displaying it, I'm not familiar with screenmanager or python. ideally the opencv and tesseract process would occur in same function as the capture however i cant get the output recognised on the following screen. heres some code, any suggestions and help appreciated!
# Importing the libraries
import cv2
import pytesseract
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen
pytesseract.pytesseract.tesseract_cmd = r'D:/pytesseract/tesseract.exe'
# voice_text = ""
# for i in ocrtext.split():
# voice_text += i + ' '
# voice_text = voice_text[:-1]
# voice_text
# engine = pyttsx3.init()
# engine.setProperty("rate", 145)
# voices = engine.getProperty('voices')
# engine.setProperty('voice', voices[0].id)
# engine.say(voice_text)
# engine.runAndWait()
class CameraScreen(Screen):
def capture(self):
camera = self.ids['camera']
camera.export_to_png("./picforocr.png")
image = cv2.imread("./picforocr.png")
ocrtext = pytesseract.image_to_string(image)
class TextScreen(Screen):
pass
GUI = Builder.load_string("""
GridLayout:
cols: 1
ScreenManager:
id: screen_manager
CameraScreen:
name: "camera_screen"
id: camera_screen
TextScreen:
name: "text_screen"
id: text_screen
<CameraScreen>:
orientation: 'vertical'
GridLayout:
cols: 1
Camera:
id: camera
resolution: (800, 800)
Button:
text: 'OCR!'
size_hint_y: None
height: '48dp'
on_press:
root.capture()
# root refers to <CameraScreen>
# app refers to TestCamera, app.root refers to the GridLayout: at the top
app.root.ids['screen_manager'].transition.direction = 'left'
app.root.ids['screen_manager'].current = 'text_screen'
<TextScreen>:
Label:
id: ocr_output
text:
Camerascreen.ocrtext
font_size: 20
Button:
text: "Do OCR Again"
size_hint_y: None
height: '48dp'
font_size: 50
on_press:
app.root.ids['screen_manager'].transition.direction = 'right'
app.root.ids['screen_manager'].current = 'camera_screen'
""")
class MyOCRApp(App):
def build(self):
return GUI
if __name__ == "__main__":
MyOCRApp().run()
This is basic code for passing texts from one class to another and also TextInput data. This is python code:
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.uix.label import Label
from kivy.uix.screenmanager import ScreenManager, Screen, SlideTransition
class FirstPage(FloatLayout):
def switch_screen(self):
secondpage = self.login_name = self.ids.login_name.text
myapp.secondpage.update_name1(secondpage)
secondpage = self.password_name = self.ids.password_name.text
myapp.secondpage.update_name2(secondpage)
myapp.screen_manager.transition = SlideTransition(direction='left', duration=.25)
myapp.screen_manager.current = 'SecondPage'
class SecondPage(FloatLayout):
def switch_back(self):
myapp.screen_manager.transition = SlideTransition(direction='right', duration=.25)
myapp.screen_manager.current = 'FirstPage'
def update_name1(self, name_login):
self.ids.name_login.text = (f'{name_login}:')
def update_name2(self, name_password):
self.ids.name_password.text = (f'{name_password}:')
class MyApp(App):
def build(self):
self.screen_manager = ScreenManager()
self.firstpage = FirstPage()
screen = Screen(name='FirstPage')
screen.add_widget(self.firstpage)
self.screen_manager.add_widget(screen)
self.secondpage = SecondPage()
screen = Screen(name='SecondPage')
screen.add_widget(self.secondpage)
self.screen_manager.add_widget(screen)
return self.screen_manager
myapp = MyApp()
myapp.run()
And this is kivy code:
FirstPage:
<FirstPage>:
TextInput:
id: login_name
size_hint: .65, .08
multiline: False
font_size: 20
pos_hint: {'x': .2, 'y': .57}
TextInput:
id: password_name
size_hint: .65, .08
multiline: False
font_size: 20
pos_hint: {'x': .2, 'y': .47}
Button:
text: "First"
size_hint: .1, .1
on_release: root.switch_screen()
<SecondPage>:
Button:
text: "Second"
size_hint: .1, .1
on_release: root.switch_back()
Label:
id: name_login
text: "Login"
size_hint: .2, .2
pos_hint: {'x': .2, 'y': .57}
Label:
id: name_password
text: "Password"
size_hint: .2, .2
pos_hint: {'x': .2, 'y': .47}

Python Kivy. My program should append the textfile, but is does not

Textfile should look like this :
e.g
Walking 61.0/2018-09-04 79.0/2018-10-04
Running 24.0/2018-09-04 33.0/2018-10-04
The point of this function is to append the textfile with the new value of the slider or to change one.
There are some names for the slider and each of them can have many values which consist of a slider.value and the current date. If today is not the date of the last value - then we append the file.
If today is the same date as the date of the last value - then it is supposed to change it(I did not do it yet, but this is not a problem, i will do it myself after I solve this problem).
Here is the full Python file and Kivy files, nothing but def save_values matters. Everything else is just to make the program working for you.
Python
from kivy.app import App
import time
import datetime
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.lang import Builder
from kivy.uix.slider import Slider
from kivy.uix.widget import Widget
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.config import Config
screen_width = 450
screen_height = 800
Config.set("graphics", "resizable","1")
Config.set("graphics", "width", screen_width)
Config.set("graphics", "height", screen_height)
languages = ["Reading","Writing","Running","Climbing"]
spawned_List = ["False"]
class MenuScreen(Screen):
pass
class JobChoiceScreen(Screen):
def changing_screen(self, instance, *args):
self.manager.current= "sliderScreen"
screenSlider = self.manager.get_screen('sliderScreen')
text = str(instance.text)
screenSlider.changing_label(text)
def on_pre_enter(self, *args):
if spawned_List[0] == "False":
for x in range(0,len(languages)):
word = languages[x]
word = str(word)
btn = Button(text = word, size_hint=(None, None), size = (140,70),
font_size = 18, bold = True, color = [0,1,1,1], background_color = (.156, .172, .24, 0.7),
on_release = self.changing_screen)
self.ids.container.add_widget(btn)
spawned_List[0] = "True"
self.ids.boxLayBottom.add_widget(Widget(size_hint=(1, .4)))
self.ids.datesContainer.add_widget(Button(text = "Day back", size_hint=(.28, 1), font_size = 18, bold = True, color = [0,1,1,1], background_color = (.176, .192, .44, 0.7)))
self.ids.datesContainer.add_widget(Widget(size_hint=(.44, 1)))
self.ids.datesContainer.add_widget(Button(text = "Day forward", size_hint=(.28, 1), font_size = 18, bold = True, color = [0,1,1,1], background_color = (.176, .192, .44, 0.7)))
class SliderScreen(Screen):
def save_values(self, *args, **kwargs):
date = (datetime.datetime.now().strftime("%y-%m-%d"))
written = (str(self.ids.my_slider.value)+ "/" + date + " ")
print("started save_values")
with open('values.txt', 'r') as fileValues:
lines = fileValues.readlines()
print("opened the file")
with open('values.txt', 'a') as fileValues:
for i, line in enumerate(lines):
if line.startswith(self.ids.my_label.text) and line.find(date) == -1:
line = line + ((self.ids.my_label.text) + " " + written)
print(line)
if not line.startswith(self.ids.my_label.text) and line.find(date) == -1:
line = (" " + written)
print(line)
print("hello bill")
def changing_label(self, text):
self.ids.my_label.text = text
class ScreenManagement(ScreenManager):
pass
presentation = Builder.load_file("manager.kv")
class MainApp(App):
def build(self):
return presentation
if __name__ == "__main__":
MainApp().run()
Kivy
ScreenManagement:
#transition: FadeTransition()
MenuScreen:
JobChoiceScreen:
SliderScreen:
<MenuScreen>:
canvas:
Rectangle:
source:"background.jpg"
pos: self.pos
size: self.size
name: "menu"
BoxLayout:
padding: [10,10,10,10]
orientation: "vertical"
Widget:
size_hint: [1,0.2]
BoxLayout:
Button:
bold: True
color: [0,1,1,1]
on_release: app.root.current = "list_of_jobs"
text: "Change"
size_hint: [0.28,1]
font_size: 20
background_color: (.156, .172, .24, 0.7)
Widget:
size_hint: [0.44,1]
Button:
bold: True
color: [.5,0, .8, .7]
text: "View \n Progress"
size_hint: [0.28,1]
font_size: 20
halign: "center"
valign: "center"
background_color: (.156, .172, .24, 0.7)
on_release: app.root.current = "sliderScreen"
Widget:
size_hint: [1,0.2]
<JobChoiceScreen>:
canvas:
Rectangle:
source:"background.jpg"
pos: self.pos
size: self.size
name: "list_of_jobs"
BoxLayout:
orientation: "vertical"
padding: [10,10,10,10]
BoxLayout:
orientation: "vertical"
id: boxLayBottom
size_hint: (1,.1)
BoxLayout:
id: datesContainer
orientation: "horizontal"
size_hint: (1,.6)
AnchorLayout:
anchor_x: "center"
acnhor_y: "top"
size_hint: (1,.8)
GridLayout:
id: container
cols: 3
spacing: 5
BoxLayout:
orientation: "vertical"
id: boxContainer
size_hint: (1,.1)
Button:
text: "Back to Menu"
on_release: app.root.current = "menu"
bold: True
color: [0,1,1,1]
background_color: (.176, .192, .44, 0.7)
<SliderScreen>:
canvas:
Rectangle:
source:"background.jpg"
pos: self.pos
size: self.size
name: "sliderScreen"
BoxLayout:
padding: [10,10,10,10]
orientation: "vertical"
id: my_label_container
Slider:
id: my_slider
min: 0
max: 100
value: 0
orientation: "vertical"
size_hint: [1, 0.7]
step: 1
Label:
id: my_label
size_hint: [1, 0.2]
bold: True
font_size: 40
text: ""
Button:
size_hint: [1, 0.1]
bold: True
on_release: app.root.current = "menu"
text : "Back Home"
font_size: 20
halign: "center"
valign: "center"
background_color: (.156, .172, .24, 0.7)
on_press: root.save_values()
def save_values
def save_values(self, *args, **kwargs):
date = (datetime.datetime.now().strftime("%y-%m-%d"))
written = (str(self.ids.my_slider.value)+ "/" + date + " ")
print("started save_values")
with open('values.txt', 'r') as fileValues:
lines = fileValues.readlines()
print("opened the file")
with open('values.txt', 'a') as fileValues:
for i, line in enumerate(lines):
if line.startswith(self.ids.my_label.text) and line.find(date) == -1:
line = line + ((self.ids.my_label.text) + " " + written)
print(line)
if not line.startswith(self.ids.my_label.text) and line.find(date) == -1:
line = (" " + written)
print(line)
print("hello bill")
I see two problems with your code:
In your save_values() method, You are opening the values.txt file twice at the same time with the same name, but with different modes. I think you need to unindent the second with open block, remove the second with open statement, and modify the mode in the first with open statement to r+. So your code should look something like:
with open('values.txt', 'r+') as fileValues:
lines = fileValues.readlines()
print("opened the file")
for i, line in enumerate(lines):
You never call any write routine, so nothing gets written. When you want to append line/lines to values.txt, you need to call fileValues.write() or fileValues.writelines().
I have not looked at your code logic, so I will not comment on that.

Categories

Resources