Python - Kivy - Hiding a widget as soon as screen shows up - python

I want to hide the progress bar at below code as soon as screen appears. In order to do that I defined a hide_widget function and added the code to "on_pre_enter" section. However it doesn't work. What am I missing here ?
By the way if you can introduce a shorter way to hide a widget in kivy, it is also very welcome.
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang import Builder
Builder.load_string("""
<MyLayout>
BoxLayout:
orientation: "vertical"
size: root.width, root.height
spacing: 20
padding: 50
Button:
text: "Test"
ProgressBar:
id: pgb_excel_read
min: 0
max: 100
value: 0
size_hint: ( 1, 0.1)
""")
def hide_widget(wid, dohide=True):
if hasattr(wid, 'saved_attrs'):
if not dohide:
wid.height, wid.size_hint_y, wid.opacity, wid.disabled = wid.saved_attrs
del wid.saved_attrs
elif dohide:
wid.saved_attrs = wid.height, wid.size_hint_y, wid.opacity, wid.disabled
wid.height, wid.size_hint_y, wid.opacity, wid.disabled = 0, None, 0, True
class MyLayout(Widget):
def on_pre_enter(self, *args):
hide_widget(self.ids.pgb_excel_read, True)
class MyApp(App):
def build(self):
return MyLayout()
if __name__ == '__main__':
MyApp().run()

on_pre_enter function is only avaliable for Screen classes. But you try to use it in your custom Widget. So there is a nothing to trigger this function. We can trigger it by __init__:
class MyLayout(Widget):
def __init__(self):
super(MyLayout, self).__init__()
hide_widget(self.ids.pgb_excel_read, True)
For hide any widget we just need to change 2 things:
Disabled : True
Opacity : 0
Short way to do that, lets stop triggering any function and just change variables: (Also Remove hide_widget function)
class MyLayout(Widget):
def __init__(self):
super(MyLayout, self).__init__()
# hide_widget(self.ids.pgb_excel_read, True)
self.ids.pgb_excel_read.opacity = 0
self.ids.pgb_excel_read.disabled = True

Related

Add points to a live graph from a different file

I'm trying to get a live graph working in my code.
I can get a live graph working when everything is within the same python file, though when I try to separate the graph class into its own python file, the graph doesn't update. I have no real indication of why the graph isn't updating, but I think I may be creating a bunch of LogGraph objects as opposed to adding points to the actual LogGraph which is in my.kv, but I am not sure how to not do that.
My actual code is a bit involved and confusing, so I mocked up an example code here which should be behaving exactly the same:
main.py
from math import sin
import kivy
from kivy_garden.graph import Graph, MeshLinePlot
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.uix.boxlayout import BoxLayout
from kivy.clock import Clock
from data import startdata
class MainWindow(Screen):
def pressrun(self):
self.ids.runlbl.text = 'Started'
startdata()
pass
class MyApp(App):
def build(self):
wm.add_widget(MainWindow())
return wm
class WindowManager(ScreenManager):
def __init__(self, **kwargs):
super(WindowManager, self).__init__(**kwargs)
wm = WindowManager()
kv = Builder.load_file("my.kv")
MyApp().run()
my.kv
#: import LogGraph graphs.LogGraph
<MainWindow>:
id: main
BoxLayout:
orientation: "vertical"
LogGraph:
BoxLayout:
orientation: "horizontal"
Button:
text: "Start Data Gen"
on_release:
root.pressrun()
Label:
id: runlbl
text: "Not Started"
graphs.py
from kivy_garden.graph import Graph, MeshLinePlot
class LogGraph(Graph):
def __init__(self, **kwargs):
super(LogGraph, self).__init__(**kwargs)
self.xlabel = 'X'
self.ylabel = 'Y'
self.x_ticks_major = 25
self.x_ticks_minor = 5
self.x_grid_label = True
self.y_ticks_major = 1
self.y_grid_label = True
self.xmin = 0
self.xmax = 100
self.ymin = 0.1
self.ymax = 10
self.ylog = True
self.x_grid = True
self.y_grid = True
self.plot = MeshLinePlot(color=[1, 0, 0, 1])
self.add_plot(self.plot)
self.plot.points = [(1,1)]
def update_xaxis(self,xmin = 0):
self.xmin = xmin
self.xmax = xmin + 10
def update_yaxis(self,ymin = 0):
self.ymin = ymin
self.ymax = ymin + 10
def update_points(self, point, *args):
self.plot.points.append([point,point])
# x axis resize
if point > self.xmax:
self.update_xaxis(self.xmax)
# y axis resize
if point > self.ymax:
self.update_yaxis(self.ymax)
data.py
from kivy.clock import Clock
from functools import partial
from graphs import LogGraph
class DataStore():
def __init__(self):
self.i = 1
self.dataarray = []
def start(self):
self.clock = Clock.schedule_interval(self.getData, 1/60)
def cancel(self):
self.clock.cancel()
def wait(self):
print('Waited!')
def getData(self):
i = self.i + 1/60
LogGraph.update_points(LogGraph(), i)
pass
def startdata():
ds = DataStore()
ds.start()
Three main problems with your code:
Your code kv = Builder.load_file("my.kv") is loading the my.kv file a second time. It will be loaded automatically because the file is named correctly for that to happen. You should eliminate that code.
Your scheduled calls to DataStore.getData() will not work because your DataStore instance is not saved anywhere, and so it gets garbage collected.
The getData() method of DataStore creates a new instance of LogGraph each time it runs, but does not use the instance of LogGraph that is in your GUI.
To fix these problems, start by adding to your kv to allow access:
#: import LogGraph graphs.LogGraph
<MainWindow>:
id: main
name: 'main' # added to enable access
BoxLayout:
orientation: "vertical"
LogGraph:
id: graph # added to enable access
BoxLayout:
orientation: "horizontal"
Button:
text: "Start Data Gen"
on_release:
root.pressrun()
Label:
id: runlbl
text: "Not Started"
Then in the startdata() method, add a return
def startdata():
ds = DataStore()
ds.start()
# return the DataStore instance so it can be saved
return ds
Then save the returned DataStore in the pressrun() method:
def pressrun(self):
self.ids.runlbl.text = 'Started'
self.dataStore = startdata()
And the getData() method must be modified to access the LogGraph that is in the GUI:
def getData(self, dt): # time interval argument is required
self.i += dt
# access the LogGraph instance in the GUI
lg = App.get_running_app().root.get_screen('main').ids.graph
lg.update_points(self.i)
# LogGraph.update_points(LogGraph(), i)

python kivy app stops functioning after adding widget (on PC)

I removed everything superfluous, leaving only what was necessary to reproduce the same behavior.
There is an MD Text Field in which, when entering text, if there are matches, MDDropdownMenu appears with options to choose from. The options are stored in the P_LIST list. If you don't enter text into this Mytextfield, everything works. As soon as you enter the text, the function is triggered, a menu appears, you select. After that, the application does not function.
I determined that this is happening because of the line: self.add_widget(list drop down) # <----------- marked in the code
The menu appears without add_widget, but if you enter more than one letter, a new instance of the ListDropdownValue class is created each time and the menus overlap.
#kivymd 0.104.2
#kivy 2.0.0
from kivy.clock import Clock
from kivy.lang import Builder
from kivy.metrics import dp
from kivy.properties import ObjectProperty
from kivymd.app import MDApp
from kivy.uix.boxlayout import BoxLayout
from kivymd.uix.menu import MDDropdownMenu
kv_str = """
<StartScreen>:
startscreen_textfield_1: textfield_id
BoxLayout:
orientation: "vertical"
BoxLayout:
size_hint: 1, 0.5
BoxLayout:
size_hint: 1, 0.5
orientation: "vertical"
BoxLayout:
MDTextField:
id: textfield_id
on_text:
root.open_listdropdown(textfield_id)#
BoxLayout:
MDTextField:
BoxLayout:
MDTextField:
"""
P_LIST = ["ASD", "SDF", "AASD"]
def search_product(prefix):
filtered_list = []
filtered_list = list(filter(lambda l: l.startswith(prefix), P_LIST))
return filtered_list
class MyListDropdownValue(MDDropdownMenu):
def __init__(self, dropdown_list, **kwargs):
super().__init__(**kwargs)
self.dropdown_list_id = dropdown_list
def list_dropdown(self):
if len(self.dropdown_list_id.text) != 0:
prefix = self.dropdown_list_id.text.upper()
filtered_list = search_product(prefix)
menu_items = [{'text':f'{value}',
"height": dp(56),
"viewclass": "OneLineListItem",
"on_release": lambda x= f"{value}": self.set_item(x)}
for value in filtered_list]
self.menu = MDDropdownMenu(
caller=self.dropdown_list_id,
items=menu_items,
width_mult=5,
)
self.menu.open()
def set_item(self, value):
def set_item(interval):
self.dropdown_list_id.text = value
self.menu.dismiss()
Clock.schedule_once(set_item, 0.1)
class StartScreen(BoxLayout):
startscreen_textfield_1 = ObjectProperty()
def open_listdropdown(self, id):
if len(self.children) == 1:
listdropdown = MyListDropdownProduct(id)
self.add_widget(listdropdown)
self.children[0].list_dropdown()
else:
self.children[0].menu.dismiss()
self.children[0].list_dropdown()
kv = Builder.load_string(kv_str)
class Program(MDApp):
def build(self):
self.screen = StartScreen()
return self.screen
def main():
app = Program()
app.run()
if __name__ == "__main__":
main()
Your MyListDropdownValue(MDDropdownMenu) class inherits from a MDDropdownMenu.
Then you make dropdown instance with
openlistdrop_down = MyDropdownValue(id)
Then you add that instance every time you "on_text" with
self.add_widget(listdropdown)
So you are adding multiple dropdowns.
In Kv try changing
on_text:
root.open_listdropdown(textfield_id)
To
on_validate:
root.open_listdropdown(textfield_id)
Then the user will need to hit enter before the list is made instead of with every letter added.

(Kivy Python) Switching Screens on Button Press Inside .py file

I understand that it is relatively easy to switch screens in the .kv file using on_release. I want to keep my button creating in the .py file, however, so I do not want to use this method. I have done the following to add a function that occurs when the 14th button is pressed. When the button is pressed in the program nothing happens. Experimenting with other names for the screen to sm.current to threw the error: "kivy.uix.screenmanager.ScreenManagerException: No Screen with name "InputScreen" when the 14th button was pressed."
# Kivy Formatting
kv_text='''\
<MyScreenManager>:
LandingScreen:
InputScreen:
<InputScreen#Screen>:
name: 'input_sc'
AnchorLayout:
id: anchor_1
<LandingScreen#Screen>:
name: 'landing_sc'
GridLayout:
id: grid_1
cols: 5
height: 480
width: 800
spacing: 25, 20
padding: 25,25
'''
# Screen Manager
class MyScreenManager(ScreenManager):
pass
# Main screen with button layout
class LandingScreen(Screen):
def __init__(self, **kwargs):
super(LandingScreen, self).__init__(**kwargs)
self.buttons = [] # add references to all buttons here
Clock.schedule_once(self._finish_init)
# IDs have to be used here because they cannot be applied until widget initialized
def _finish_init(self, dt):
self.ids.grid_1.cols = 5
# Loop to make 15 different buttons on screen
for x in range(15):
self.buttons.append(Button(text='button {}'.format(x)))
self.ids.grid_1.add_widget(self.buttons[x])
self.buttons[x].background_normal = 'YOUTUBE.png'
def SwitchScreen(self,*args):
sm.current = 'input_sc'
sm = ScreenManager()
sm.add_widget(InputScreen(name='input_sc'))
sm.add_widget(LandingScreen(name='landing'))
self.buttons[14].bind(on_release=SwitchScreen)
# Input screen
class InputScreen(Screen):
pass
class MySubApp(App):
def build(self):
return MyScreenManager()
def main():
Builder.load_string(kv_text)
app = MySubApp()
app.run()
if __name__ == '__main__':
main()
If someone could help me understand the hole in my current logic I would appreciate it greatly. Thanks.
Each screen has a manager property that gives you the instance of the ScreenManager used. You only need to use it to refer to the ScreemManager instance and use its current method:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.button import Button
from kivy.clock import Clock
# Kivy Formatting
kv_text='''\
<MyScreenManager>:
LandingScreen:
InputScreen:
<InputScreen#Screen>:
name: 'input_sc'
AnchorLayout:
id: anchor_1
Button:
text: 'Hello'
<LandingScreen#Screen>:
name: 'landing_sc'
GridLayout:
id: grid_1
cols: 5
height: 480
width: 800
spacing: 25, 20
padding: 25,25
'''
# Screen Manager
class MyScreenManager(ScreenManager):
pass
# Main screen with button layout
class LandingScreen(Screen):
def __init__(self, **kwargs):
super(LandingScreen, self).__init__(**kwargs)
self.buttons = [] # add references to all buttons here
Clock.schedule_once(self._finish_init)
# IDs have to be used here because they cannot be applied until widget initialized
def _finish_init(self, dt):
self.ids.grid_1.cols = 5
# Loop to make 15 different buttons on screen
for x in range(15):
self.buttons.append(Button(text='button {}'.format(x)))
self.ids.grid_1.add_widget(self.buttons[x])
self.buttons[x].background_normal = 'YOUTUBE.png'
self.buttons[14].bind(on_release=self.switch_screen)
def switch_screen(self, *args):
self.manager.current = 'input_sc'
# Input screen
class InputScreen(Screen):
pass
class MySubApp(App):
def build(self):
return MyScreenManager()
def main():
Builder.load_string(kv_text)
app = MySubApp()
app.run()
if __name__ == '__main__':
main()

How to trigger an action once on overscroll in Kivy?

I have a ScrollView that's supposed to have an update feature when you overscroll to the top (like in many apps). I've found a way to trigger it when the overscroll exceeds a certain threshold, but it triggers it a lot of times, as the on_overscroll event is triggered on every movement. So is there a way to limit it?
My code looks like this:
from kivy.app import App
from kivy.uix.scrollview import ScrollView
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.effects.dampedscroll import DampedScrollEffect
class Effect(DampedScrollEffect):
def on_overscroll(self, *args):
super().on_overscroll(*args)
if self.overscroll < -50:
print('hey')
class TestApp(App):
def build(self):
sv = ScrollView(effect_cls = Effect,
size_hint_y = 0.2)
gl = GridLayout(cols = 1,
size_hint_y = None)
gl.bind(minimum_height = gl.setter('height'))
for i in range(5):
gl.add_widget(Button(text = str(i),
size_hint = (None, None)))
sv.add_widget(gl)
return sv
TestApp().run()
So, as you can see, when the overscroll goes beyond 50, it prints a simple message. But when you actually try it, you'll see that it prints it many times. What I want for it is to trigger an event, stay untriggerable for some time (like a second) and update the content. I've tried messing with boolean flags and Clock, but it didn't work. What could be done here?
I would use a stateful decorator here:
class call_control:
def __init__(self, max_call_interval):
self._max_call_interval = max_call_interval
self._last_call = time()
def __call__(self, function):
def wrapped(*args, **kwargs):
now = time()
if now - self._last_call > self._max_call_interval:
self._last_call = now
function(*args, **kwargs)
return wrapped
class Effect(DampedScrollEffect):
def on_overscroll(self, *args):
super().on_overscroll(*args)
if self.overscroll < -50:
self.do_something()
#call_control(max_call_interval=1)
def do_something(self):
print('hey')
I know this an old question but someone might find it useful
This is a sample from tshirtman's github gist
from threading import Thread
from time import sleep
from kivy.app import App
from kivy.lang import Builder
from kivy.factory import Factory
from kivy.clock import mainthread
from kivy.properties import ListProperty, BooleanProperty
KV = '''
FloatLayout:
Label:
opacity: 1 if app.refreshing or rv.scroll_y > 1 else 0
size_hint_y: None
pos_hint: {'top': 1}
text: 'Refreshing…' if app.refreshing else 'Pull down to refresh'
RecycleView:
id: rv
data: app.data
viewclass: 'Row'
do_scroll_y: True
do_scroll_x: False
on_scroll_y: app.check_pull_refresh(self, grid)
RecycleGridLayout:
id: grid
cols: 1
size_hint_y: None
height: self.minimum_height
default_size: 0, 36
default_size_hint: 1, None
<Row#Label>:
_id: 0
text: ''
canvas:
Line:
rectangle: self.pos + self.size
width: 0.6
'''
class Application(App):
data = ListProperty([])
refreshing = BooleanProperty()
def build(self):
self.refresh_data()
return Builder.load_string(KV)
def check_pull_refresh(self, view, grid):
max_pixel = 200
to_relative = max_pixel / (grid.height - view.height)
if view.scroll_y < 1.0 + to_relative or self.refreshing:
return
self.refresh_data()
def refresh_data(self):
Thread(target=self._refresh_data).start()
def _refresh_data(self):
self.refreshing = True
sleep(2)
self.append_data([
{'_id': i, 'text': 'hello {}'.format(i)}
for i in range(len(self.data), len(self.data) + 50)
])
self.refreshing = False
#mainthread
def append_data(self, data):
self.data = self.data + data
if __name__ == "__main__":
Application().run()

Kivy references across screens

I want to access root widgets ids from other rootwidgets, but I can't seem to fully grasp how referencing works in Kivy and using a ScreenManager with different screens makes it even harder for me.
I want to achieve the following:
Edit: single file version
(This code assumes you're going to build a complex app, so I don't want to load all code at startup. Hence the kv_strings are loaded when switching screen, and not put into kv code of the ScreenManager. Code is based on the Kivy Showcase.)
Code main.py, Edit 2: working code (see answer why)
#!/usr/bin/kivy
# -*- coding: utf-8 -*-
from kivy.app import App
from kivy.uix.screenmanager import Screen
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.clock import Clock
from kivy.properties import StringProperty, ObjectProperty
kv_foo = '''
<FooScreen>:
id: fooscreen_id
BoxLayout:
id: content
orientation: 'vertical'
spacing: '20dp'
padding: '8dp'
size_hint: (1, 1)
BoxLayout:
orientation: 'vertical'
Label:
id: important_text
size_hint_y: 0.3
text: app.imp_text
Button:
id: magic_change
size_hint_y: 0.3
text: "Change text above to text below (after screen switch)"
on_press: app.change_text()
ScreenManager:
id: sm
on_current_screen:
idx = app.screen_names.index(args[1].name)
'''
class FooScreen(Screen):
# 'content' refers to the id of the BoxLayout in FooScreen in foo.kv
def add_widget(self, *args):
if 'content' in self.ids:
return self.ids.content.add_widget(*args)
return super(FooScreen, self).add_widget(*args)
class FooApp(App):
imp_text = StringProperty("Should change to text from id: magic_text")
screen_magic = ObjectProperty()
magic_layout = ObjectProperty()
def build(self):
self.title = 'Foo'
self.root = root = Builder.load_string(kv_foo)
# Trying stuff with References
self.sm = self.root.ids.sm # ScreenManager
# Setting up screens for screen manager
self.screens = {}
self.available_screens = [kv_mainmenu, kv_magic]
self.screen_names = ['MainMenu', 'Magic']
self.go_screen(0)
# Go to other screen
def go_screen(self, idx):
print("Change MainScreen to: {}".format(idx))
self.index = idx
# Go to not main menu
if idx == 0:
self.root.ids.sm.switch_to(self.load_screen(idx), direction='right')
# Go to main menu
else:
self.root.ids.sm.switch_to(self.load_screen(idx), direction='left')
# Load kv files
def load_screen(self, index):
if index in self.screens:
return self.screens[index]
screen = Builder.load_string(self.available_screens[index])
self.screens[index] = screen
# if index refers to 'Magic' (kv_magic), create reference
if index == 1:
Clock.schedule_once(lambda dt: self.create_reference())
return screen
# Trying to get id's
def create_reference(self):
print("\nrefs:")
# Get screen from ScreenManager
self.screen_magic = self.sm.get_screen(self.screen_names[1])
# screen.boxlayout.magiclayout
self.magic_layout = self.screen_magic.children[0].children[0]
def change_text(self):
# Get text from id: magic_text
if self.magic_layout:
self.imp_text = self.magic_layout.ids['magic_text'].text
kv_mainmenu = '''
FooScreen:
id: mainm
name: 'MainMenu'
Button:
text: 'Magic'
on_release: app.go_screen(1)
'''
kv_magic = '''
<MagicLayout>
id: magic_layout
orientation: 'vertical'
Label:
id: magic_text
text: root.m_text
FooScreen:
id: magic_screen
name: 'Magic'
MagicLayout:
id: testmagic
'''
class MagicLayout(BoxLayout):
m_text = StringProperty("Reference between widgets test")
if __name__ == '__main__':
FooApp().run()
Question
How can I set up proper references that the button "Change text above..." can retrieve magic_text.text ("Reference between widgets test") and change self.imp_text to magic_text.text?
I found a way to reference to Kivy widgets not loaded at the startup of the app without using globals. Thanks #inclement for ScreenManager.get_screen().
I had to add the following code:
class FooApp(App):
screen_magic = ObjectProperty()
magic_layout = ObjectProperty()
...
# Trying to get id's
def create_reference(self):
print("\nrefs:")
# Get screen from ScreenManager
self.screen_magic = self.sm.get_screen(self.screen_names[1])
# screen.boxlayout.magiclayout
self.magic_layout = self.screen_magic.children[0].children[0]
def change_text(self):
# Get text from id: magic_text
if self.magic_layout:
self.imp_text = self.magic_layout.ids['magic_text'].text
self.screen_magic is assigned the screen I need (<FooScreen>) and self.magic_layout is assigned the widget I need (<MagicLayout>). Then I can use the ids from <MagicLayout> to access the Label magic_text's text.
(For full code see updated question)

Categories