Hi I am new to Kivy and I am trying to make a GUI using kivy to deploy machine learning model. I am importing a data set with drag and drop feature in kivy but I want to change the label to file path after I drag and drop the csv file.
Here is my code:
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.image import Image
from kivy.uix.button import Button
from kivy.core.window import Window
import pandas as pd
from kivy.uix.textinput import TextInput
class Amplicon_Coverage_Prediction(App):
def build(self):
self.window = GridLayout()
self.window.cols = 1
# Drag and drop feature initialize
Window.bind(on_drop_file = self.on_file_drop)
#add widgets to window
# adding Image to widget
self.window.add_widget(Image(source = "DNA.png"))
# Label Widget
self.head = Label(text = "Amplicon Coverage Prediction")
self.window.add_widget(self.head)
# File Path to CSV Label
self.label_csv_path = Label(text = "Please choose a csv file to begin")
self.window.add_widget(self.label_csv_path)
self.csv_button = Button(text = "Choose CSV",
size_hint = (1, 0.5))
self.window.add_widget(self.csv_button)
self.csv_button.bind(on_press = self.call_csv_path)
self.csv_button.bind(on_press=self.load_csv)
return self.window
# Calling drag and drop feature
def on_file_drop(self, window, path_to_csv, x, y):
self.path_to_csv = str(path_to_csv)
self.path_to_csv = self.path_to_csv[2:(len(self.path_to_csv) -1)]
def call_csv_path(self, instace):
self.label_csv_path.text = self.path_to_csv
return self.path_to_csv
def load_csv(self, instace):
self.dataset = pd.read_csv('/' + self.path_to_csv[1:])
print(self.dataset.head())
if __name__ == "__main__":
Amplicon_Coverage_Prediction().run()
Related
I've coded this little app with Kivy that has 3 textbox + 1 dropdown:
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.popup import Popup
class Inremapp(App):
def AddDropDownButton(self, name):
self.btn = Button(text=name, size_hint_y=None, height=44)
self.btn.bind(on_release=lambda btn: self.dropdown.select(self.btn.text))
self.dropdown.add_widget(self.btn)
def build(self):
self.operaciones = ["1", "123", "1241", "124121"]
self.window = GridLayout()
self.window.cols = 1
self.window.size_hint = (0.6, 0.7)
self.window.pos_hint = {"center_x": 0.5, "center_y":0.5}
# entrada
labelentrada = Label(text='Entrada: (Día/Mes/Año)')
self.window.add_widget(labelentrada)
txtinday = TextInput(text='', multiline=False)
self.window.add_widget(txtinday)
# salida
labelsalida = Label(text='Salida: (Día/Mes/Año)')
self.window.add_widget(labelsalida)
txtoutday = TextInput(text='', multiline=False)
self.window.add_widget(txtoutday)
# obra
txtobra = TextInput(text='Obra', multiline=False)
self.window.add_widget(txtobra)
# operación
self.dropdown = DropDown()
for operacion in self.operaciones:
self.AddDropDownButton(operacion)
mainbutton = Button(text='Operación')
mainbutton.bind(on_release=self.dropdown.open)
self.dropdown.bind(on_select=lambda instance, x: setattr(mainbutton, 'text', x))
self.window.add_widget(self.dropdown)
self.window.add_widget(mainbutton)
return self.window
# run app
if __name__ == "__main__":
Inremapp().run()
The app looks like this when running:
But when I click the dropdown button I get the following error:
Exception has occurred: WidgetException Cannot add
<kivy.uix.dropdown.DropDown object at 0x000002D18787E6C0> to window,
it already has a parent <kivy.uix.gridlayout.GridLayout object at
0x000002D1873CEF10> File "D:\Inrema\TabletConnect\main.py", line 68,
in
Inremapp().run()
The basic example from Kivy docs is working fine but... what I'm missing in my code?
EDIT:
After removing self.window.add_widget(self.dropdown) error disappeared, dropdown is showing up but when I select any element I will always get the latest value, doesn't matters what I select.
EDIT 2:
Changed this line:
self.btn.bind(on_release=lambda btn: self.dropdown.select(self.btn.text))
To this:
self.btn.bind(on_release=lambda btn: self.dropdown.select(btn.text))
And worked fine :)
I am trying to make tambola coin picker with Python and Kivy and I am new to kivy.
Here, I created gridlayout buttons from 1 to 90. I want to change the color of particular button in gridlayout when its number is picked. I am facing issues to update gridlayout with new colored button. Here I am attaching my code. screenshot
#!/usr/bin/python
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.gridlayout import GridLayout
from kivy.graphics import Color
import random
coins = random.sample(range(1,91), 90)
#print(coins)
picked_coins=[]
current_coin=0
#print(picked_coins)
class Housie(FloatLayout):
def __init__(self,**kwargs):
super(Housie,self).__init__(**kwargs)
self.title = Label(text="Housie Coin Picker",font_size = 50,size_hint=(1, .55),pos_hint={'x':0, 'y':.45})
self.main_label = Label(text = "Click PICK NUMBER", size_hint=(1, .60),pos_hint={'x':0, 'y':.35})
self.picked_ones = Label(text = "picked_coins", size_hint=(1, .40),pos_hint={'x':0, 'y':.40})
self.help_button = Button(text = "PICK NUMBER", size_hint=(.3, .1),pos_hint={'x':.65, 'y':.1},on_press = self.update)
self.add_widget(self.title)
self.add_widget(self.main_label)
self.add_widget(self.picked_ones)
self.add_widget(self.help_button)
self.add_widget(self.userinterface())
def userinterface(self):
self.layout = GridLayout(cols = 10,size_hint=(.50, .50))
for i in range(1,91):
self.layout.add_widget(Button(background_color=(1,0,0,1),text =str(i)))
return self.layout
def update(self,event):
for coin in coins:
if coin not in picked_coins:
current_coin=coin
picked_coins.append(coin)
self.main_label.text = str(coin)
for i in self.layout.children:
if i.text == str(coin):
#What to do Here?
break
self.picked_ones.text = "Picked coins = {}".format(" ".join(str(sorted(picked_coins))))
class app1(App):
def build(self):
return Housie()
if __name__=="__main__":
app1().run()
You can bind a method to each Button like this:
def userinterface(self):
self.layout = GridLayout(cols = 10,size_hint=(.50, .50))
for i in range(1,91):
self.layout.add_widget(Button(background_color=(1,0,0,1),text=str(i), on_release=self.butt_pressed))
return self.layout
def butt_pressed(self, button):
button.background_normal = ''
button.background_color = (1,0,0,1)
Th butt_pressed() method changes the background color of the pessed Button.
So i manage to get focus in the TextInput > tracknumb. at start of the app, but still when i confirm the input, finally i can do it with enter now too, but it looses the focus from textinput once i submit it.
Can you please advice what am I missing?
Whole Code here
import kivy
import kivy
import mysql.connector
from datetime import datetime
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.image import Image
from kivy.core.audio import SoundLoader
from kivy.core.window import Window
from kivy.clock import Clock
Window.size = (480, 800)
class MyGrid(GridLayout):
def __init__(self, **kwargs):
super(MyGrid, self).__init__(**kwargs)
self.cols = 1 # Set columns for main layout
self.inside = GridLayout(cols=2, row_force_default=True,
row_default_height=50, padding=20,
spacing=10) # Create a new grid layout
self.add_widget(Label(text="Tracking Number \n Checker", halign="center", font_size=40)) # Top Label
self.inside.add_widget(Label(text="Work Number:", halign="center", font_size=20)) # Add a label widget
self.worknumb = TextInput(text_validate_unfocus=True, multiline=False, font_size=20, halign="center")
self.inside.add_widget(self.worknumb)
self.inside.add_widget(Label(text="Tracking \nNO. Scan:", halign="center", font_size=20))
self.tracknumb = TextInput(multiline=False, font_size=15, halign="center") # Create a Text input box stored in the name variable
self.inside.add_widget(self.tracknumb) # Add the text input widget to the GUI
self.add_widget(self.inside) # Add the interior layout to the main
self.submit = Button(text="Submit", font_size=40, size_hint =(.5, .5)) # Submit button
self.add_widget(self.submit)
self.submit.bind(on_press=self.send_tracknumb)
self.resultbox = Image(source="status.png") #image box on bottom
self.add_widget(self.resultbox)
Window.bind(on_key_down=self.pressed)
Clock.schedule_once(self.focus_tracknumb, 1)
def pressed(self, instance, keyboard, keycode, text, modifiers):
if keycode == 40 or keycode == 13:
self.send_tracknumb(None)
def focus_tracknumb(self, _):
self.tracknumb.focus = True
def send_tracknumb(self, _):
tracknumb = self.tracknumb.text
worknumb = self.worknumb.text
errorsound = SoundLoader.load("incorrect.mp3") # add sound to the scanning
correctsound = SoundLoader.load("correct.ogg")
self.tracknumb.text = "" # Reset text to blank in each text input
I think you can change focus back to the TextInput in the pressed() method:
def pressed(self, instance):
tracknumb = self.tracknumb.text
worknumb = self.worknumb.text
errorsound = SoundLoader.load("incorrect.mp3") #add sound to the scanning
correctsound = SoundLoader.load("correct.ogg")
self.tracknumb.text = "" # Reset text to blank in each text input
self.tracknumb.focus = True # Change focus back to tracknumb
Och dong, I missed it :D it was so simple, I had to put the function to that part
def send_tracknumb(self, _):
I missed that one in all the text :{
Clock.schedule_once(self.focus_tracknumb, 0.1)
I am new to kivy. I have chosen a background image and i want to insert a label on it. But it shows like this.
from kivy.app import App
from kivy.uix.image import Image
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
class MyApp(App):
def build(self):
self.box = BoxLayout()
self.img = Image(source = 'image4.png')
self.lbl = Label(text = "Total_Wealth")
self.box.add_widget(self.img)
self.box.add_widget(self.lbl)
return self.box
[![enter image description here][1]][1]MyApp().run()
The BoxLayout automatically stacks the widgets.
If you want to put Label on top of the image, you can use FloatLayout for more control on the placement of the widgets
I am trying to build an app that downloads a file, whose progress can be tracked on a kivy app.
I have looked at the example here and here for the download progress.
This is my code:
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.popup import Popup
from kivy.factory import Factory
from kivy.properties import ObjectProperty
from kivy.clock import Clock
import urllib
URL = "http://s9.videozoo.me/S/saenai_heroine_no_sodatekata_flat_-_11.mp4?st=Ow7pwXbRt6vPWE-kr5Sn1A&e=1498847899&start=0"
class PopupBox(Popup):
pop_up_text = ObjectProperty()
def update_pop_up_text(self, p_message):
self.pop_up_text.text = p_message
class MyApp(App):
# layout
def show_popup(self):
self.pop_up = Factory.PopupBox()
self.pop_up.update_pop_up_text('Running some task...')
self.pop_up.open()
def build(self):
layout = BoxLayout(padding=10, orientation='vertical')
btn1 = Button(text="OK")
btn1.bind(on_press=self.buttonClicked)
layout.add_widget(btn1)
self.lbl1 = Label(text="test")
layout.add_widget(self.lbl1)
self.txt1 = TextInput(text='', multiline=False)
layout.add_widget(self.txt1)
return layout
# button click function
def buttonClicked(self, btn):
self.lbl1.text = "You wrote " + self.txt1.text
self.show_popup()
self.download_file(URL)
self.pop_up.dismiss()
def download_file(self, url):
u = urllib.request.urlopen(url)
meta = u.info()
metaInfo = str(meta).split()
fileTotalbytes = int(metaInfo[46])
data_blocks = []
total = 0
while True:
block = u.read(1024)
data_blocks.append(block)
total += len(block)
hash = ((60 * total) // fileTotalbytes)
print("[{}{}] {}%".format('#' * hash, ' ' * (60 - hash), int(total / fileTotalbytes * 100)), end="\r")
if not len(block):
break
data = b''.join(data_blocks) # had to add b because I was joining bytes not strings
u.close()
# run app
if __name__ == "__main__":
MyApp().run()
However, I am confused as to how do I bind the download_file function with the kivy widget functionality so as to make it work. How do I appropriately modify the print function so as to make it work with the widget
If you block in the mainthread kivy can no longer update the GUI. Instead create a new thread and use the #mainthread annotation to do gui updates.
Instead of the print you have to manipulate kivy widgets. You could create a rectangle and increase the width to 100%. You could create a textinput and output your text there.