I came across an AssertionError for a kivy script. The codes as follows:
import time
from copy import deepcopy as dc
# import modules related to kivy UI
from kivy.app import App
# kivy.require("1.9.1")
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.image import Image
# define global variables just for testing
temperature = str(25)+"°C"
humidity = str(95)+'%'
last_water = "15/04/2018 15:40"
time_next = str(4)+' hr'
kv = """
<LeftScreen>:
GridLayout:
cols: 2
Image:
id: im
source: 'C:/Users/Acer/Documents/Python Scripts/sakura.jpg'
size_hint: 0.5, 0.5
Label:
id: title
text: '[b][i]Smart[/i]'+' Gardener[/b]'
color: (0.25,0.5,0.1,1)
font_size: 60
font_name: 'times'
Label:
id: group
text: '[i]group 8[/i]'
color: (0.3,0.3,0.6,1)
font_size: 45
font_name: 'Arial'
valign: 'bottom'
Label:
id: lastU
text: '[i]'+'Last Update: '+time.striftime("%H:%M:%S")+'[/i]'
font_size: 18
halign: 'center'
valign: 'middle'
Button:
id: update
text: 'Refresh'
font_size: 20
halign: 'center'
valign: 'middle'
on_press: root.reload()
Label:
id: temp_lbl
text: 'Temperature: '
font_size: 24
halign: 'center'
valign: 'middle'
Label:
id: temp_val
text: root.temp
font_size: 24
halign: 'center'
valign: 'middle'
Label:
id: hum_lbl
text: 'Humidity: '
font_size: 24
halign: 'center'
valign: 'middle'
Label:
id: hum_val
text: root.hum
font_size: 24
halign: 'center'
valign: 'middle'
Label:
id: lastW_lbl
text: 'Last Watering: '
font_size: 24
halign: 'center'
valign: 'middle'
Label:
id: lastW_val
text: root.last_water
font_size: 24
halign: 'center'
valign: 'middle'
Label:
id: nextW_lbl
text: 'Time before Next Watering: '
font_size: 24
halign: 'center'
valign: 'middle'
Label:
id: nextW_val
text: root.time_text
font_size: 24
halign: 'center'
valign: 'middle'
"""
Builder.load_string(kv)
# create the left screen
class LeftScreen(Screen):
def __init__(self, **kwargs):
super(LeftScreen, self).__init__(**kwargs)
self.temp = dc(temperature)
self.hum = dc(humidity)
self.last_water = dc(last_water)
self.time_next = dc(time_next)
def reload(self,value):
self.ids.lastU.text='Last Update: '+time.strftime("%H:%M:%S")
self.ids.temp_val.text=temperature
self.ids.hum_val.text=humidity
self.ids.lastW_val.text=last_water
self.ids.nextW_val.text=time_next
class RightScreen(Screen):
def __init__(self,**kwargs):
super(RightScreen,self).__init__(**kwargs)
self.layout = GridLayout()
self.add_widget(self.layout)
class SmartGardener(App):
def build(self):
sm = ScreenManager()
ls = LeftScreen(name='data')
sm.add_widget(ls)
sm.current = 'data'
return sm
def reset():
import kivy.core.window as window
from kivy.base import EventLoop
if not EventLoop.event_listeners:
from kivy.cache import Cache
window.Window = window.core_select_lib('window', \
window.window_impl, True)
Cache.print_usage()
for cat in Cache._categories:
Cache._objects[cat] = {}
myApp = SmartGardener()
if __name__ == '__main__':
reset()
myApp.run()
Is the error with the image that I inserted or the variables I used for the labels? I want to insert the image as the background of the UI.
Also, there seems to be some error with the variable 'time_next' when I tried to accessing it from the kivy file. What is the right way to access the attribute 'time_next' of object MainScreen in the kv quote?
Okay, i tried to run your code and here is what i found:
you try to access 'time_text' in kv file, while you set in the class 'time_next', that's a typo but even after i fixed it i had to set defaults in the kv file for all the variables that you call, hum, temp, time_next, last_water:
<LeftScreen>:
time_text: ''
last_water:''
hum: ''
temp: ''
GridLayout:
cols: 2
...
next you use the time.striftime which is a typo to time.strftime, yet you need to import it in the kv code like so:
:import strftime time.strftime
<LeftScreen>:
...
and use it like:
Label:
id: lastU
text: '[i]'+'Last Update: '+strftime("%H:%M:%S")+'[/i]'
see the kv language docs for it: under special syntax
i wasn't able to run your code yet, i didn't have the Fonts you used, so i simply commented those lines, and once it ran i noticed that the Label's show the markup, to use it you need to explicitly set markupe=True
Label:
id: title
text: '[b][i]Smart[/i]'+' Gardener[/b]'
markup: True
color: (0.25,0.5,0.1,1)
font_size: 60
#font_name: 'times'
Label:
id: group
text: '[i]group 8[/i]'
markup: True
color: (0.3,0.3,0.6,1)
font_size: 45
#font_name: 'Arial'
valign: 'bottom'
At last, clicking the refresh button calls reload without any value, while it expects some value, so the 'refresh' button would raise a TypeError.
Related
I´m learning kivy, and it has passed 3 weeks since i face this problem without encounter a solution, so i hope any of u guys could help me, i would appreciate it.
I have a main file:
from app import MyProgramApp
if __name__ == "__main__":
winapp = MyProgramApp()
winapp.run()
from where i start my app. Then i have a directory called "app", inside there is the following "init.py" file.
from kivy.app import App
from kivy.utils import QueryDict, rgba
from kivy.core.window import Window
from .view import MainWindow
Window.minimum_width = 500
Window.minimum_height = 650
Window.maximize()
class MyProgramApp(App):
colors = QueryDict()
colors.primary = rgba('#2D9CDB')
colors.secondary = rgba('#16213E')
colors.succes = rgba('#1FC98E')
colors.warning = rgba('#F2C94C')
colors.danger = rgba('#E85757')
colors.grey_dark = rgba('#C4C4C4')
colors.grey_light = rgba('#F5F5F5')
colors.black = rgba('#A1A1A1')
colors.white = rgba('#FFFFFF')
def build(self):
return MainWindow()
Same folder app, i have the following "view.py".
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.behaviors import ToggleButtonBehavior
from kivy.properties import StringProperty
from kivy.uix.screenmanager import ScreenManager
class MainWindow(BoxLayout):
username = StringProperty("Usuario")
def __init__(self, **kw):
super().__init__(**kw)
def on_press_home(self):
self.ids.scrn_mngr.current = "scrn_home"
class ViewManager(ScreenManager):
def __init__(self, **kw):
super().__init__(**kw)
class NavTab(ToggleButtonBehavior, BoxLayout):
text = StringProperty('')
icon = StringProperty('')
def __init__(self, **kw):
super().__init__(**kw)
and finally for that folder i have "myprogram.kv"
#:kivy 2.1.0
#:import Home views.home.Home
<MainWindow>:
spacing: dp(8)
canvas.before:
Color:
rgba: app.colors.white
Rectangle:
pos: self.pos
size: self.size
# NAVIGATION BAR
BoxLayout:
id: nav_menu
size_hint_x: .2
orientation: "vertical"
size_hint_min_x: dp(100)
# LOGO
BoxLayout:
id: logo_nbox
size_hint_y: .1
size_hint_min_y: dp(70)
padding: dp(16)
AnchorLayout:
anchor_x: "right"
size_hint_x: None
width: dp(52)
halign: "left"
Label:
text: "COMPANY"
halign: "center"
BoxLayout:
orientation: "vertical"
Label:
text: "COMPANY"
halign: "center"
Label:
text: "Phrase"
halign: "center"
# OPTIONS
GridLayout:
id: tabs_box
cols: 1
spacing: dp(4)
size_hint_y: .5
canvas.before:
Color:
rgba: app.colors.grey_dark
Rectangle:
pos: self.pos
size: [self.size[0], dp(1)]
NavTab:
text: "Home"
state: "down"
on_press: root.on_press_home()
# BODY
BoxLayout:
size_hint_x: .8
spacing: dp(8)
orientation: "vertical"
padding: [dp(16), dp(8), dp(12), dp(8)]
canvas.before:
Color:
rgba: app.colors.grey_light
Rectangle:
pos: self.pos
size: self.size
# SCREENS
BoxLayout:
ViewManager:
id: scrn_mngr
<ViewManager>:
Screen:
name: "scrn_home"
Home:
id: home
<NavTab>:
background_normal: ""
background_down: ""
background_color: [0,0,0,0]
group: "tabs"
size_hint_y: None
height: dp(45)
spacing: dp(4)
canvas.before:
Color:
rgba: [0,0,0,0] if self.state == "normal" else rgba("#E1F1FF")
Rectangle:
pos: self.pos
size: self.size
Color:
rgba: [0,0,0,0] if self.state == "normal" else app.colors.primary
Rectangle:
pos: [self.pos[0]+self.size[0]-dp(1), self.pos[1]]
size: [dp(8), self.size[1]]
Label:
halign: "left"
valign: "middle"
text: root.text
color: app.colors.grey_dark if root.state == "normal" else app.colors.primary
Then i got another folder called "views" inside i have another folder called "home", inside home we encounter 3 files "init.py", "home.kv", "home.py". the first one "init.py" is the following.
from .home import Home
then we got "home.kv".
#:kivy 2.1.0
<Home>:
orientation: "vertical"
Label:
size_hint_y: .1
text: "Other"
Button:
size_hint_y: .1
text: "popup"
on_press: root.open_popup()
BoxLayout:
size_hint_y: .8
id: home_box
<SomePopup>:
title: "SOME TITLE"
title_align: "center"
title_color: app.colors.primary
size_hint: .25, .8
size_hint_min_x: dp(200)
pos_hint: {"x": .1, "top": .9}
BoxLayout:
orientation: "vertical"
padding: [dp(0), dp(12), dp(0), dp(12)]
Label:
text: "Some text"
Button:
text: "create buttons on box"
on_press: root.modify_home_box()
and finally and the problem that i´m facing is whit the following file "home.py"
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.factory import Factory
from kivy.uix.popup import Popup
from kivy.uix.button import Button
from kivy.app import App
Builder.load_file('views/home/home.kv')
class Home(BoxLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def open_popup(self):
Factory.SomePopup().open()
class SomePopup(Popup):
def __init__(self, **kw):
super().__init__(**kw)
def modify_home_box(self):
my_app = App.get_running_app().root
my_box = my_app.ids.home.ids.home_box
custom_button = Button(
text = "something"
)
my_box.add_widget(custom_button)
That i´m trying to do is actually modify "home_box" with is store on ids Home dictionary, i also try with ObjectProperty (but that gives and Attribute Error, since i only could read propertys but doesnt modify it), instance of a new Home class doesnt work... searching for current app in App appear doesnt work since Home is store i think on screenManager...
I need add a button or some widget to "home_box" from outside class "SomePopup". I also drop here a repository on github with the whole code. github_repo
I don't know how to solve my issue, and i try with the resources available here on stack as well other net places... any help would be appreciate.
Just a very complicated path to the widget of interest. In your modify_home_box() method, try replacing:
my_app = App.get_running_app().root
my_box = my_app.ids.home.ids.home_box
with:
my_app = App.get_running_app().root
my_box = my_app.ids.scrn_mngr.ids.home.ids.home_box
I want to update MDRectangleFlatIconButton's text. It changes with a new text but when the new text is longer than previous text, then the text fits in two lines.
When i use a normal button, the new text fits in one line with proper adjustment.
but Since there is a Icon in MDRectangleFlatIconButton, when a new text is longer than previous text, the text fits in a two line.
To run the program,
Add a new app name which is longer than "Info" inside "Info" button's popup window, then click "Update Top Bar's name". Then, it updated title and the text of "Info" button at the front main App.
I have tried to change this by adding button's text_size: self.width, valign:"center", haling: "center", or manually adding text_size: cm(10), cm(10).
Also, i tried with on_release: "app.root.ids.bt_information.text_size = self.width, None
but nothing works so far.
I greatly appreciate your help.
Python code
'''
from kivy.uix.widget import Widget
'''Setting the size of first window for program'''
from kivy.config import Config #another way of setting size of window
Config.set('graphics', 'width', '600') # from kivy.core.window import Window
Config.set('graphics', 'height', '750') # Window.size = ("600", "750")
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.factory import Factory
from kivy.uix.popup import Popup
from kivy.properties import ObjectProperty
Builder.load_file('new_window_popup.kv')
class Dex(Popup):
pass
class Remi(Popup):
pass
class Info(Popup):
pass
class MyLayout(Widget):
pass
class AwesomeApp(MDApp):
def build(self):
self.title = "My house"
return MyLayout()
if __name__ == '__main__':
AwesomeApp().run()
'''
kivyfile: new_window_popup.kv
'''
#:import Factory kivy.factory.Factory
#:import MDRaisedButton kivymd.uix.button
<Dex>:
auto_dismiss: False
size_hint: 1, 1
title: "Weight-Based Dose Calculator "
canvas.before:
Color:
rgba: (0,1,0,1)
Rectangle:
pos:self.pos
size:self.size
BoxLayout:
orientation: "vertical"
size:root.width, root.height
Label:
text: "Dex 1"
Button:
text: "Close"
font_size: 24
on_release: root.dismiss()
<Remi>:
auto_dismiss: False
size_hint: 1, 1
title: "Weight-Based Dose Calculator "
canvas.before:
Color:
rgba: (0,1,0,1)
Rectangle:
pos:self.pos
size:self.size
BoxLayout:
orientation: "vertical"
size:root.width, root.height
Label:
text: "Remi"
Button:
text: "Close"
font_size: 24
on_release: root.dismiss()
<Info>:
appName:appName
auto_dismiss: False
size_hint: 1, 1
title: "Change Info"
canvas.before:
Color:
rgba: (0,1,0,1)
Rectangle:
pos:self.pos
size:self.size
BoxLayout:
orientation: "vertical"
size:root.width, root.height
Label:
text: "What is your App name?"
BoxLayout:
orientation: "horizontal"
MDTextField:
id: appName
hint_text: "App Name"
color_mode: 'primary'
current_hint_text_color: 1,1,1,1
hint_text_color_focus: 1,1,1,.9
line_color_focus: 1,1,1,1
font_size: '25sp'
text_color_normal: 1,1,1,.9
text_color_focus: 0,0,1,.9
focus: True
write_tab: False
Button:
text: "Update Top Bar\'s name"
font_size: 24
size_hint: .8, .2
# on_release: root.updateName()
on_release:
app.title = appName.text
app.root.ids.bt_information.text = appName.text
Button:
text: "Close"
font_size: 24
on_release: root.dismiss()
<MyLayout>
MDBoxLayout:
orientation:"vertical"
size: root.width, root.height
MDRaisedButton:
text: "Dex"
font_size: 32
text_color: 0,0,0,.9
size_hint: 1,.5
on_press: Factory.Dex().open()
MDRaisedButton:
text: "Remi"
font_size: 32
size_hint: 1,.5
on_press: Factory.Remi().open()
MDRectangleFlatIconButton:
id: bt_information
text: "Info"
icon: "youtube-studio"
font_size: 32
size_hint: 1,.2
text_size: self.width, None
md_bg_color: 0.95,0.61,0.73,1
on_press: Factory.Info().open()
'''
As the image below, I'm trying to set the text on the top of textField.
There's too many space between the text (above and below), so I'd like to set the text more close to the top line.
I already tried to search on kivy's documentation and here on the site, but not something helpful.
Code:
from kivymd.app import MDApp
from kivymd.uix.floatlayout import FloatLayout
from kivymd.uix.textfield import MDTextField
from kivy.lang import Builder
KV = '''
ScreenManager:
Screen:
BoxLayout:
orientation: 'vertical'
Screen:
<Screen>:
ScrollView:
MDList:
spacing: '10dp'
padding: '25dp'
MDTextField:
halign: 'center'
multiline: True
font_size: self.width / 25
MDTextField:
halign: 'center'
font_size: self.width / 25
mode: 'rectangle'
multiline: True
MDTextField:
halign: 'center'
font_size: self.width / 25
multiline: True
mode: 'fill'
'''
class Screen(FloatLayout):
pass
class Aplicativo(MDApp):
def build(self):
return Builder.load_string(KV)
Aplicativo().run()
I'm sorry if I was not comprehensive.
I'm pretty new to python and kivy and I'm trying to build my first app for my masterthesis. The problem I'm struggeling with right now is that I have multiple python and kivy files, and my app includes a group of Toggle buttons and Spinners. I want to 'store'/assign theselected values and print them when i hit my submit button. I'm working with multiple python and kivy files. The app also has some sliders and i managed to get those values when pressing submit, but can't figure it out for toggles nor spinners. I hope you can help!:)
Main .py, rather important:
import kivy
from kivy.app import App
from kivy.uix.button import Label
from kivy.uix.widget import Widget
from kivy.uix.textinput import TextInput
from kivy.lang import Builder
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import BooleanProperty
from kivy.properties import ObjectProperty
Builder.load_file('Header.kv')
Builder.load_file('Statusbar.kv')
Builder.load_file('Inputparameters.kv')
Builder.load_file('Outputparameters.kv')
#Layout
class Peenomat(AnchorLayout):
def show_selected_value(self, spinner, text):
print(spinner, text)
#pass
#DropDown in Inputparameters
#class InputParameters(BoxLayout):
#state = BooleanProperty(False)
class PeenomatApp(App):
def build(self):
return Peenomat()
if __name__=="__main__":
PeenomatApp().run()
The main kv file:
AnchorLayout:
anchor_x: 'left'
anchor_y: 'bottom'
GridLayout:
cols: 1
canvas.before:
Color:
rgba: 0.75 ,0.75, 0.75, 1
Rectangle:
pos: self.pos
size: self.size
Header:
id: _header
size_hint: 1, 0.1
#height: 100
InputParameters:
id:_input_parameters
size_hint: 1, 0.45
StatusBar:
id:_status_bar
size_hint: 1, 0.1
#height: 50
OutputParameters:
id:_output_parameters
size_hint: 1, 0.35
The .kv file that includes the toogle buttons, spinners, and sliders where i guess most of the implemantation needs to be done
#: import statusbar StatusBar
<InputParameters#GridLayout>
prozess: _proz_value
prozess1: _prozess1
prozess2: _prozess2
prozess3: _prozess3
vorbehandlung: _vorbehandlung
material: _material
haerte: _haerte
rauheit: _rauheit
cols: 2
padding: 15
spacing: 15
#Farbe Schrift Label
cb: (1,1, 1,1)
#Farbe Slider
cs: (0,0.353, 0.663,1)
#FontSize
fs: 20
#Prozess
Label:
text:'Prozess: '
bold: True
font_size: root.fs
text_size: self.size
halign: 'left'
valign: 'center'
color: root.cb
BoxLayout:
orientation: 'horizontal'
id: _proz_value
_proz_value: 0
ToggleButton:
text:'P-MOH'
id: _prozess1
group: "proc_group"
background_color: 0.0, 0.353, 0.663, 1.0
bold: True
on_press: root._proz_value = 1
ToggleButton:
text:'E-MOH'
id: _prozess2
group: "proc_group"
background_color: 0.0, 0.353, 0.663, 1.0
bold: True
on_press: root._proz_value = 2
ToggleButton:
text:'PE-MOH'
id: _prozess3
group: "proc_group"
background_color: 0.0, 0.353, 0.663, 1.0
bold: True
on_press: root._proz_value = 3
#Material
Label:
text: 'Material: '
bold: True
font_size: root.fs
text_size: self.size
halign: 'left'
valign: 'center'
color: root.cb
Spinner:
id: _material
# Callback
on_text:
text: "Auswahl treffen"
bold:True
values: ['1.2379', 'Gusseisen', 'Kautschuk', 'Carbon', 'Adamantium']
#background_normal: '[1,1,1,1]'
background_color: root.cs
color: root.cb
# Herstellschritte
Label:
text:'Fertigungsschritte: '
bold: 'True'
font_size: root.fs
text_size: self.size
halign: 'left'
valign: 'center'
color: root.cb
Spinner:
id: _vorbehandlung
# Callback
on_text:
app.root.show_selected_value(self, self.text)
text: "Auswahl treffen"
bold:True
values: ['Fräsen', 'Erodieren', 'Schleifen', 'Polieren']
#background_normal: '[1,1,1,1]'
background_color: root.cs
color: root.cb
# Haerte
Label:
text:'Haerte: '
bold: True
font_size: root.fs
text_size: self.size
halign: 'left'
valign: 'center'
color: root.cb
BoxLayout:
orientation: 'vertical'
spacing: 15
Label:
text: str(_haerte.value) + ' HRC'
color: root.cs
bold: True
Slider:
id: _haerte
min: 45
max: 65
value:55
step: 1
value_track: True
value_track_color: root.cs
# Rauheit
Label:
text:'Rauheit: '
#color: cb
bold: True
font_size: root.fs
text_size: self.size
halign: 'left'
valign: 'center'
color: root.cb
BoxLayout:
orientation: 'vertical'
spacing: 15
Label:
text: str("%.1f" % _rauheit.value) + ' Rz' #eine Nachkommastelle
color: root.cs
bold: True
Slider:
id: _rauheit
min: 1
max: 10
value:5.5
step: 0.1
value_track: True
value_track_color: root.cs
The .kv file that includes the submit button:
#: import statusbar StatusBar
<StatusBar#BoxLayout>
orientation:'horizontal'
padding: 5
fs: 16
Button:
text: 'Clear'
background_color: 0.0, 0.353, 0.663, 1.0
size_hint: 0.4, 1
bold: True
font_size: 20
on_press: root.btn_clear()
Button:
text: 'Submit'
background_color: 0.0, 0.353, 0.663, 1.0
size_hint: 0.4, 1
bold: True
font_size: 20
on_press: root.btn_submit()
and last but not the least the file that includes the methods that are assigned to the buttons, which shuld also be important for my issue:
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
from kivy.app import App
from kivy.lang import Builder
class StatusBar(BoxLayout):
group_mode = False
#translation = ListProperty(None)
prozess = ObjectProperty(None)
vorbehandlung = ObjectProperty(None)
material = ObjectProperty(None)
haerte = ObjectProperty(None)
rauheit = ObjectProperty(None)
def btn_submit(self,text):
ip = App.get_running_app().root.ids._input_parameters
print("Haerte:", ip.haerte.value, "Rauheit:", ip.rauheit.value, "Material:", ip.material.text)
def btn_clear(self):
np = App.get_running_app().root.ids._input_parameters
np.prozess1.state = "normal"
np.prozess2.state = "normal"
np.prozess3.state = "normal"
np.material.text = "Auswahl treffen"
np.haerte.value = 55
np.rauheit.value = 5.5
The App is running like this and the clear button is exactly doing what its supposed to do, but I really can't figure out how I manage to print the selected spinner and toggle values when hitting submit...I hope you guys can help, been struggeling with this since a while now. Thanks in advance!
Alright i figured out an easy way to get the spinner value when hititng submit:
def btn_submit(self):
ip = App.get_running_app().root.ids._input_parameters
print("Haerte:", ip.haerte.value, "Rauheit:", ip.rauheit.value, "Material:", ip.material.text, "Vorbehandlung:", ip.vorbehandlung.text)
to get the value of the toggle buttons i did this:
def on_state(self, togglebutton):
tb = togglebutton
if tb.state == 'down':
self.verfahren = tb.text
InputParameters.verfahren = tb.text
print(self.verfahren)
return InputParameters.verfahren
and added in the .kv file for the toggle button:
ToggleButton:
id:_prozess2
text:'E-MOH'
on_state: root.on_state(self)
I'm getting the value/state like that, but it's not triggered with the submit button, can't figure out how to do so
I'm new to kivy and I'm trying to create a drag and drop app where if the image is dropped onto the gridlayout the image is shown on the app as shown below. I'm trying to get the file_path of the image and then using the file_path to display it on the gridlayout but unfortunately, that is not working. Any help would be greatly appreciated!
This is the current image
This is what I want after dragging the image
Kv file
# Custom button
<CustButton#Button>:
font_size: 32
background_normal: 'Colour_yellow.png'
background_down: 'Colour_blue.png'
<Cust2#Button>:
font_size: 32
background_normal: 'Colour_red.png'
background_down: 'Colour_blue.png'
<Cust3#Button>:
font_size: 32
background_normal: 'Colour_white.png'
background_down: 'Colour_blue.png'
<Cust4#Button>:
font_size: 32
background_normal: 'Colour_blue.png'
background_down: 'Colour_white.png'
<CalcGridLayout>:
id: calculator
display: entry
rows: 5
padding: 10
spacing: 10
BoxLayout:
spacing: 100
size_hint: .5, None
Cust2:
text: "Whats the intensity you want?"
BoxLayout:
size_hint: .5, None
TextInput:
id: entry
font_size: 70
multiline: False
hint_text: "Type here"
BoxLayout:
spacing: 100
size_hint: .5, None
Cust4:
text: "Drag and Drop picture below:"
on_release: root.build1()
#THIS IS WHERE I'M STUCK ON
BoxLayout:
Image:
source: root._on_file_drop(file_path)
BoxLayout:
size_hint: 1, .3
spacing: 10
CustButton:
text: "Click here for \n reduced size"
CustButton:
text: "Click here for pos \n and intensity of \n each pixel"
on_release: root.reduced_image()
CustButton:
text: "Click here \n for graph"
CustButton:
text: "Click here \n for all"
CustButton:
text: "Extra"
Python file
import kivy
kivy.require("1.9.0")
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.core.window import Window
Window.clearcolor = (0.5, 0.5, 0.5, 1)
class CalcGridLayout(GridLayout):
def reduced_image(self):
#ignore
def build1(self):
Window.bind(on_dropfile=self._on_file_drop)
return
def _on_file_drop(self, window, file_path):
print(file_path)
return file_path
class dropdownApp(App):
def build(self):
return CalcGridLayout()
dropApp = dropdownApp()
dropApp.run()
Solution
Please refer to the snippets, and complete example for details.
kv file
Remove on_release: root.build1()
Replace source: root._on_file_drop(file_path) with id: img
Snippet
BoxLayout:
spacing: 100
size_hint: .5, None
Cust4:
text: "Drag and Drop picture below:"
BoxLayout:
Image:
id: img
Python Code
Add import statement, from kivy.properties import StringProperty
Declare property, filePath = StringProperty('') in class CalcGridLayout().
Add constructor to class CalcGridLayout() and move Window.bind(on_dropfile=self._on_file_drop) from build1() method
Remove build1() method
In _on_file_drop() method, replace return file_path with self.filePath = file_path.decode("utf-8") self.ids.img.source = self.filePath and self.ids.img.reload()
Snippet
from kivy.properties import StringProperty
...
class CalcGridLayout(GridLayout):
filePath = StringProperty('')
def __init__(self, **kwargs):
super(CalcGridLayout, self).__init__(**kwargs)
Window.bind(on_dropfile=self._on_file_drop)
def reduced_image(self):
print(self.filePath)
def _on_file_drop(self, window, file_path):
print(file_path)
self.filePath = file_path.decode("utf-8") # convert byte to string
self.ids.img.source = self.filePath
self.ids.img.reload() # reload image
Window » on_dropfile Event
on_dropfile(filename)
Event called when a file is dropped on the application.
Warning
This event currently works with sdl2 window provider, on pygame window
provider and OS X with a patched version of pygame. This event is left
in place for further evolution (ios, android etc.)
Example
main.py
import kivy
kivy.require("1.11.0")
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.core.window import Window
from kivy.properties import StringProperty
Window.clearcolor = (0.5, 0.5, 0.5, 1)
class CalcGridLayout(GridLayout):
filePath = StringProperty('')
def __init__(self, **kwargs):
super(CalcGridLayout, self).__init__(**kwargs)
Window.bind(on_dropfile=self._on_file_drop)
def reduced_image(self):
print(self.filePath)
def _on_file_drop(self, window, file_path):
print(file_path)
self.filePath = file_path.decode("utf-8") # convert byte to string
self.ids.img.source = self.filePath
self.ids.img.reload() # reload image
class DragDropApp(App):
def build(self):
return CalcGridLayout()
if __name__ == "__main__":
DragDropApp().run()
dragdrop.kv
#:kivy 1.11.0
# Custom button
<CustButton#Button>:
background_normal: "/home/iam/Pictures/AppImages/Colors/yellow.png" # 'Colour_yellow.png'
background_down: "/home/iam/Pictures/AppImages/Colors/blue.png" # 'Colour_blue.png'
text_size: self.size
halign: 'center'
valign: 'middle'
<Cust2#Button>:
font_size: 32
background_normal: "/home/iam/Pictures/AppImages/Colors/red.png" # 'Colour_red.png'
background_down: "/home/iam/Pictures/AppImages/Colors/blue.png" # 'Colour_blue.png'
<Cust3#Button>:
font_size: 32
background_normal: "/home/iam/Pictures/AppImages/Colors/white.png" # 'Colour_white.png'
background_down: "/home/iam/Pictures/AppImages/Colors/blue.png" # 'Colour_blue.png'
<Cust4#Button>:
font_size: 32
background_normal: "/home/iam/Pictures/AppImages/Colors/blue.png" # 'Colour_blue.png'
background_down: "/home/iam/Pictures/AppImages/Colors/white.png" # 'Colour_white.png'
<CalcGridLayout>:
id: calculator
display: entry
rows: 5
padding: 10
spacing: 10
BoxLayout:
spacing: 100
size_hint: .5, None
Cust2:
text: "Whats the intensity you want?"
BoxLayout:
size_hint: .5, None
TextInput:
id: entry
font_size: 70
multiline: False
hint_text: "Type here"
BoxLayout:
spacing: 100
size_hint: .5, None
Cust4:
text: "Drag and Drop picture below:"
BoxLayout:
Image:
id: img
BoxLayout:
size_hint: 1, .3
spacing: 10
CustButton:
text: "Click here for \n reduced size"
CustButton:
text: "Click here for pos \n and intensity of \n each pixel"
on_release: root.reduced_image()
CustButton:
text: "Click here \n for graph"
CustButton:
text: "Click here \n for all"
CustButton:
text: "Extra"
Output