def build(self):
Window.bind(keyboard_height=self.updateHeight)
if platform == 'android':
return MainWidget()
# the dreaded splash screen code
from kivy.uix.screenmanager import NoTransition, ScreenManager, Screen
from kivy.uix.image import Image
sm = ScreenManager(transition=NoTransition())
splashScr = Screen(name='SplashScreen')
splashScr.add_widget(Image(source='misc/splash-desktop.png'))
sm.add_widget(splashScr)
mainScr = Screen(name='MainScreen')
mainScr.add_widget(MainWidget())
sm.add_widget(mainScr)
def switchToMainScr(instance):
sm.current = 'MainScreen'
Clock.schedule_once(switchToMainScr, 3)
return sm
python类schedule_once()的实例源码
def build(self):
self.title = core.string_lang_title[:-1] # ????????? ???? ?????????
self.icon = "Data/Images/logo.png" # ?????? ???? ?????????
self.use_kivy_settings = False
self.config = ConfigParser()
self.config.read("{}/program.ini".format(core.prog_path))
self.beep = SoundLoader.load("Data/mess_unread.wav")
self.set_variable_from_settings()
# ???????? ???????? ???????.
self.start_screen = \
StartScreen(name_buttons_menu=core.name_buttons_menu,
buttons_menu=core.buttons_menu,
buttons_group=core.buttons_group,
previous="Data/Images/logo.png",
title_previous=core.string_lang_title[:-1],
title_image="Data/Images/DV.png",
overflow_image="Data/Images/overflow_image.png",
previous_image="Data/Images/previous_image.png",
events_callback=self.events_program)
self.screen = self.start_screen
Clock.schedule_once(self.read_license, 3)
return self.start_screen
def show_about(self):
def events_callback(instance_label, text_link):
def answer_callback(answer):
if answer in [core.string_lang_click_dimonvideo_redirect,
core.string_lang_click_ptyhon_redirect,
core.string_lang_click_kivy_redirect]:
webbrowser.open(answer.replace("www.", r"http:\\"))
if text_link in ["HeaTTheatR", "Virtuos86", "dimy44"]:
Clock.schedule_once(
lambda *args: self.send_mail_or_show_profile(text_link),
0.1)
else:
self.create_window(
callback=answer_callback, param="query",
text=core.text_for_about[text_link]["text"],
button_ok=core.text_for_about[text_link]["ok"],
button_cancel=core.text_for_about[text_link]["cancel"])
AboutDialog(events_callback=events_callback,
background_image=core.theme_decorator_window,
name_program=core.string_lang_about_name_program,
logo_program="Data/Images/logo.png",
info_program=core.info_program)
def animate_in_big(self, focus_input=True):
self.size = self.big_size
self.selected_size = 'big'
if self.pos_multiplier < 1.0:
if self.pos_multiplier:
d = self.anim_speed * (1.0 - (self.pos_multiplier))
else:
d = self.anim_speed
anim = Animation(pos_multiplier=1.0, d=d, t='out_quad')
anim.start(self)
self.ids.rv.scroll_to_end()
else:
d = 0.05
self.ids.inputw.is_focusable = True
if focus_input:
Clock.schedule_once(self.focus_input, d * 3.0)
def by_text(self, text):
root = App.get_running_app().root
found = False
for widget in root.walk():
if hasattr(widget, 'text') and text in widget.text:
if hasattr(widget, 'on_press'):
found = True
widget.on_press()
Clock.schedule_once(widget.on_release, 0.2)
ret = '# Pressed button %s' % (widget)
break
elif hasattr(widget, 'on_left_click'):
found = True
widget.on_left_click()
ret = '# Pressed button %s' % (widget)
break
if not found:
ret = '# Did not find button'
return ret
def remove_from_focus(self, prev_focus=False):
'''Remove widget from focusable_widgets or focus_grab_widgets list'''
global current_focus, prev_focused_widgets, focus_grab_widgets
global prev_focused_widgets
if current_focus == self:
remove_focus()
if self.grab_focus and self in focus_grab_widgets:
focus_grab_widgets.remove(self)
elif self in focusable_widgets:
focusable_widgets.remove(self)
remlist = [
i for i, x in enumerate(prev_focused_widgets) if x() == self]
for x in reversed(remlist):
del prev_focused_widgets[x]
if prev_focus:
Clock.schedule_once(set_focus_previous, 0)
def submit(self):
ids = self.ids
time = ids.time.text
date = ids.date.text
bg = ids.bg.text
carbs = ids.carbs.text
bolus = ids.bolus.text
notes = ids.notes.text
if time != '' and date != '' and (bg != '' or carbs != '' or bolus != '' or notes != ''):
if bg == '':
bg = 0
if carbs == '':
carbs = 0
if bolus == '':
bolus = 0
if notes == '':
notes = ' '
datetime = date + ' ' + time
self.dm.new_entry(datetime, bg, carbs, bolus, notes)
Clock.schedule_once(datascreen.refresh, 2)
self.dismiss()
def build(self):
self.root = NotificationDemo(self)
if platform == 'android':
try:
self.service = autoclass(
'org.test.npexample.ServiceMyservice')
mActivity = autoclass(
'org.kivy.android.PythonActivity').mActivity
argument = ''
self.service.start(mActivity, argument)
except:
self.service = AndroidService(
'Sevice example', 'service is running')
self.service.start('Hello From Service')
else:
Window.system_size = cm(7), cm(12)
self.client.on_connect = self.on_connect
self.client.on_disconnect = self.on_disconnect
Clock.schedule_once(self.try_connecting, 0)
Clock.schedule_interval(self.handle_msg, 0.1)
# def skipp(*a):
# self.root.ids.sm.current = 'main'
# Clock.schedule_once(skipp, 0.5)
return self.root
def dropAnim(self, fall):
# Animace padání bloku
if fall:
d = .1
else:
d= .2
boxes = []
for box in self.shape[self.orientation]:
if ((box[0] >= 0) and (box[0] <= 11)) and ((box[1] >= 0) and (box[1] <= 21)):
cur = self.get(box[0], box[1])
a = Box()
a.size = cur.size
a.pos = cur.pos
a.colored = cur.colored
a.size_hint = (None, None)
boxes.append(a)
self.app.sOverlay.add_widget(a)
if len(boxes) != 0:
anims = [Animation(y=p.y-p.size[1], opacity=0., t='linear', d=d) for p in boxes]
for i in range(len(boxes)):
anims[i].start(boxes[i])
Clock.schedule_once(self.clearAnimation, d)
def __init__(self, **kwargs):
self.theme_manager = ThemeManager()
self.setup_font_ramps()
self.get_color = get_rgba_color
self.get_icon = get_icon_char
self.get_style = get_style
self.get_ramp_group = get_font_ramp_group
super(FlatApp, self).__init__(**kwargs)
self.setup_themes()
self.numpads = numpads = {}
numpads['decimal'] = DecimalNumPad()
numpads['regular'] = NumPad()
if self.do_device_id:
log_behavior = LogBehavior()
self.log_manager = log_manager = log_behavior.log_manager
self.settings_interface = settings_interface = DBInterface(
construct_target_file_name('', __file__), 'settings')
self.device_id = device_id = settings_interface.get_entry(
'settings', 'device_id', 'value')
self.bind(device_id=log_manager.setter('device_id'))
if device_id is None:
Clock.schedule_once(self.register_device_id)
def trigger_action(self, duration=0.1):
'''Trigger whatever action(s) have been bound to the button by calling
both the on_press and on_release callbacks.
This simulates a quick button press without using any touch events.
Duration is the length of the press in seconds. Pass 0 if you want
the action to happen instantly.
.. versionadded:: 1.8.0
'''
self._do_press()
self.dispatch('on_press')
def trigger_release(dt):
self._do_release()
self.dispatch('on_release')
if not duration:
trigger_release(0)
else:
Clock.schedule_once(trigger_release, duration)
def __init__(self, **kw):
super(CircularTimePicker, self).__init__(**kw)
self.selector_color = self.theme_cls.primary_color[0], self.theme_cls.primary_color[1], \
self.theme_cls.primary_color[2]
self.color = self.theme_cls.text_color
self.primary_dark = self.theme_cls.primary_dark[0] / 2, self.theme_cls.primary_dark[1] / 2, \
self.theme_cls.primary_dark[2] / 2
self.on_ampm()
if self.hours >= 12:
self._am = False
self.bind(time_list=self.on_time_list,
picker=self._switch_picker,
_am=self.on_ampm,
primary_dark=self._get_ampm_text)
self._h_picker = CircularHourPicker()
self.h_picker_touch = False
self._m_picker = CircularMinutePicker()
self.animating = False
Clock.schedule_once(self.on_selected)
Clock.schedule_once(self.on_time_list)
Clock.schedule_once(self._init_later)
Clock.schedule_once(lambda *a: self._switch_picker(noanim=True))
def on_touch_up( self, touch ):
global minUITimer
global lightOffTimer
if touch.grab_current is self:
touch.ungrab( self )
with thermostatLock:
Clock.unschedule( light_off )
if minUITimer != None:
Clock.unschedule( show_minimal_ui )
minUITimer = Clock.schedule_once( show_minimal_ui, minUITimeout )
lighOffTimer = Clock.schedule_once( light_off, lightOff )
GPIO.output( lightPin, GPIO.HIGH )
self.manager.current = "thermostatUI"
log( LOG_LEVEL_DEBUG, CHILD_DEVICE_SCREEN, MSG_SUBTYPE_TEXT, "Full" )
return True
##############################################################################
# #
# Kivy Thermostat App class #
# #
##############################################################################
def on_touch_down(self, touch):
if not self.collide_point(*touch.pos):
touch.ud[self._get_uid('cavoid')] = True
return
if self._touch:
return super(BrowsingCard, self).on_touch_down(touch)
Animation.cancel_all(self)
self._touch = touch
uid = self._get_uid()
touch.grab(self)
touch.ud[uid] = {
'mode': 'unknown',
'time': touch.time_start}
Clock.schedule_once(self._change_touch_mode,
self.scroll_timeout / 1000.)
return True
def on_touch_up(self, touch):
if self._get_uid('cavoid') in touch.ud:
return
if self in [x() for x in touch.grab_list]:
touch.ungrab(self)
self._touch = None
ud = touch.ud[self._get_uid()]
if ud['mode'] == 'unknown':
Clock.unschedule(self._change_touch_mode)
super(BrowsingCard, self).on_touch_down(touch)
Clock.schedule_once(partial(self._do_touch_up, touch), .1)
else:
self._start_animation()
else:
if self._touch is not touch and self.uid not in touch.ud:
super(BrowsingCard, self).on_touch_up(touch)
return self._get_uid() in touch.ud
def on_touch_up( self, touch ):
global minUITimer
if touch.grab_current is self:
touch.ungrab( self )
with thermostatLock:
if minUITimer != None:
Clock.unschedule( show_minimal_ui )
minUITimer = Clock.schedule_once( show_minimal_ui, minUITimeout )
self.manager.current = "thermostatUI"
log( LOG_LEVEL_DEBUG, CHILD_DEVICE_SCREEN, MSG_SUBTYPE_TEXT, "Full" )
return True
##############################################################################
# #
# Kivy Thermostat App class #
# #
##############################################################################
def complete(self, text=_('Complete'), show_time=2):
"""
Sets the progress to 100%, hides the button(s) and automatically
closes the popup.
.. versionchanged:: 0.2.1
Added parameters 'text' and 'show_time'
:param text: text instead of 'Complete', optional
:param show_time: time-to-close (in seconds), optional
"""
self._complete = True
n = self.max
self.value = n
self.text = text
self.buttons = []
Clock.schedule_once(self.dismiss, show_time)
def make_line(self):
if not self.line_lock:
#Lock the button down for a better user experience
self.line_lock = True
Logger.info("Locked!")
Clock.schedule_once(self.unlock, 18.00)
pos = pconsole.get_position()
while not pos:
pos = pconsole.get_position()
Logger.info("self.x is at: " + str(self.x) + " position x is at: " + str(pos[0]))
if self.mode == "L2R":
if float(pos[0]) < self.max_x_travel:
self._line()
else:
self.warn_and_restart()
elif self.mode == "R2L":
if float(pos[0]) > self.max_x_travel:
self._line()
else:
self.warn_and_restart()
def __init__(self, populate=True, **kwargs):
super(UpdateScreen, self).__init__()
self.data_path = roboprinter.printer_instance.get_plugin_data_folder()
self.repo_info_url = 'https://api.github.com/repos/mcecchi/Update_Script/releases'
self.repo_local_path = self.data_path + '/Update_Script'
self.updater_path = self.repo_local_path + '/Update_Checker/Update_Checker.py'
self.repo_remote_path = 'https://github.com/mcecchi/Update_Script.git'
self.versioning_path = self.data_path + '/roboOS.txt'
self.printer_model = roboprinter.printer_instance._settings.get(['Model'])
#populate version numbers when screen gets initiated
self.populate = populate
if self.populate:
Clock.schedule_once(self.populate_values)
def end_print(self, dt):
try:
#make new object for the printer
idle_screen = Idle_Screen()
#clear widgets from the screen
content_space = self.ids.printer_content
content_space.clear_widgets()
content_space.clear_widgets()
#add Idle Screen
content_space.add_widget(idle_screen)
except AttributeError as e:
Logger.info("Error in End Print")
Clock.schedule_once(self.end_print, 1)
Logger.info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! "+ str(e))
traceback.print_exc()
def show(self):
self.show_schedule_handle = None
self.ready = self.check_ready()
if self.ready:
self.shown = True
self.remove_old()
self.on_show(self.get_fade_duration())
else:
if self.old_action and self.time.now() - self.action['time'] > fade_old_max_wait:
self.remove_old()
self.show_schedule_handle = Clock.schedule_once(lambda dt: self.show(), 0)
def _update(self, *args):
result = False
if self.builds == []:
raise Exception('No builds updates available, did you forget to check_update()?')
self.logging('No builds updates available, did you forget to check_update()?')
try:
self.download_file(self.builds[-1]['link'])
self.extract_files(fpath=self.update_path+'temp.zip')
if self.prompts:
Clock.schedule_once(lambda x: self.update_done_dialog(self.own_ver, self.builds[-1]['ver']), 0)
result = True
except Exception as e:
self.logging('Update crashed')
self.logging(traceback.format_exc())
for x in self.on_update:
x(result)
def _update(self, *args):
result = False
if self.builds == []:
raise Exception('No builds updates available, did you forget to check_update()?')
self.logging('No builds updates available, did you forget to check_update()?')
try:
self.download_file(self.builds[-1]['link'])
self.extract_files(fpath=self.update_path+'temp.zip')
if self.prompts:
Clock.schedule_once(lambda x: self.update_done_dialog(self.own_ver, self.builds[-1]['ver']), 0)
result = True
except Exception as e:
self.logging('Update crashed')
self.logging(traceback.format_exc())
for x in self.on_update:
x(result)
def make_line(self):
if not self.line_lock:
#Lock the button down for a better user experience
self.line_lock = True
Logger.info("Locked!")
Clock.schedule_once(self.unlock, 18.00)
pos = pconsole.get_position()
while not pos:
pos = pconsole.get_position()
Logger.info("self.x is at: " + str(self.x) + " position x is at: " + str(pos[0]))
if self.mode == "L2R":
if float(pos[0]) < self.max_x_travel:
self._line()
else:
self.warn_and_restart()
elif self.mode == "R2L":
if float(pos[0]) > self.max_x_travel:
self._line()
else:
self.warn_and_restart()
def __init__(self, populate=True, **kwargs):
super(UpdateScreen, self).__init__()
self.data_path = roboprinter.printer_instance.get_plugin_data_folder()
self.repo_info_url = 'https://api.github.com/repos/robo3d/Update_Script/releases'
self.repo_local_path = self.data_path + '/Update_Script'
self.updater_path = self.repo_local_path + '/Update_Checker/Update_Checker.py'
self.repo_remote_path = 'https://github.com/Robo3d/Update_Script.git'
self.versioning_path = self.data_path + '/roboOS.txt'
self.printer_model = roboprinter.printer_instance._settings.get(['Model'])
#populate version numbers when screen gets initiated
self.populate = populate
if self.populate:
Clock.schedule_once(self.populate_values)
def end_print(self, dt):
try:
#make new object for the printer
idle_screen = Idle_Screen()
#clear widgets from the screen
content_space = self.ids.printer_content
content_space.clear_widgets()
content_space.clear_widgets()
#add Idle Screen
content_space.add_widget(idle_screen)
except AttributeError as e:
Logger.info("Error in End Print")
Clock.schedule_once(self.end_print, 1)
Logger.info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! "+ str(e))
traceback.print_exc()
def test_ui_base(self):
app = main.PyWalletApp()
p = partial(self.run_test, app)
Clock.schedule_once(p, 0.000001)
app.run()
def __init__(self, **kwargs):
super(NavigationDrawerTwoLineListItem, self).__init__(**kwargs)
Clock.schedule_once(lambda dt: self.setup())
def __init__(self, **kwargs):
super(Receive, self).__init__(**kwargs)
# for some reason setting the timeout to zero
# crashes with:
# 'super' object has no attribute '__getattr__'
# only on first account creation (with auto redirect)
# and we cannot yet reproduce in unit tests
timeout = 1
Clock.schedule_once(lambda dt: self.setup(), timeout)
def __init__(self, **kwargs):
super(History, self).__init__(**kwargs)
Clock.schedule_once(lambda dt: self.setup())