I am populating a treeview in Kivy that takes some time depending on how large it is.
In the case the tree is large and takes awhile, I would like to display a popup while it is populating so the user is aware the program has not frozen, and close this popup when the logic for populating the tree finishes.
Here is what I have come up with through some research on the topic, but the popup still seems to only come once the tree is finished populating:
def show(self, *args):
self.error_popup.open()
def populate_tree(self, model):
#Clock.schedule_once(self.error_popup.open())
popup_thread = threading.Thread(target=self.show())
popup_thread.start()
# order the dictionary for better user experience
ordered_data = collections.OrderedDict(sorted(model.items()))
# logic to populate tree
for county, value in ordered_data.items():
if county != "model_name":
# set initial county dropdowns in tree
county_label = self.treeview.add_node(TreeViewButton(text=str(county), on_press=self.edit_node))
i = 0 # keep count of rules
# add rules children to county
for rule_obj, rule_list in value.items():
for rule in rule_list:
i += 1
# set rule number in tree
rule_label = self.treeview.add_node(TreeViewButton(text='Rule ' + str(i), on_press=self.edit_node), county_label)
# add conditions children to rule
for condition in rule:
self.treeview.add_node(TreeViewButton(text=condition, on_press=self.edit_node), rule_label)
#Clock.schedule_once(self.error_popup.dismiss())
#somehow close popup_thread
I included a kivy Clock attempt in case that is more on the right track of what I am looking for, however currently it will just open the popup and never populate the tree. I am new to GUI programming and event callbacks, so any help is greatly appreciated.
I tried keeping the code short, if more is needed please let me know.
I built an app which does something similar to what you're doing (different computation, but as you said the point was it was time-consuming and you want to thread a popup that shows the app isn't crashed - it's just crankin' the numbers). What ended up working for me was to set up a button to execute a dummy function which toggles both the popup and the calculation. Run the popup first and then thread the calculation through the 'from threading import Thread' module to execute the computation on a separate thread.
Here's a working example. It's just sleeping for 5 seconds but you can stick your computation into that function and it should work just fine. What it does is opens the popup before the computation and closes the popup when the calculation is done. Also, you can stick a 'Loading.gif' file into the folder and it'll import that as your loading gif if you want to use something other than what kivy pulls up (which is essentially a loading gif for loading your Loading.gif which isn't loading because it's not there... haha). Also added an 'ABORT' button if your user gets tired of waiting.
Finally just as a side note, I've had difficulties getting the .kv file to build into the pyinstaller application bundeler, so just as a heads up, using the builder.load_string(KV) function is a good alternative for that.
from threading import Thread
from sys import exit
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.popup import Popup
from kivy.lang import Builder
KV = '''
<Pop>:
id:pop
title: ''
auto_dismiss: False
padding: 10
spacing: 10
BoxLayout:
BoxLayout:
padding: 10
spacing: 10
orientation: 'vertical'
Label:
font_size: 22
size_hint_y: None
text_size: self.width, None
height: self.texture_size[1]
text: "Process is currently running."
Label:
id: error_msg
size_hint_x: 0.3
text: ''
BoxLayout:
orientation: 'vertical'
Button:
background_color: (1,0,0,1)
text: "ABORT"
on_press: root.sysex()
AsyncImage:
source: 'Loading.gif'
<MetaLevel>:
rows: 1
cols: 1
Button:
text: 'RUN'
on_release: root.dummy()
'''
Builder.load_string(KV)
class MetaLevel(GridLayout):
def dummy(self, *args):
App.get_running_app().pop.open()
Thread(target=self.calculate, args=(args,), daemon=True).start()
def calculate(self, *args):
import time
time.sleep(5)
App.get_running_app().pop.dismiss()
class Pop(Popup):
def sysex(self):
exit()
class Cruncher(App):
def build(self):
self.pop = Pop()
return MetaLevel()
if __name__ == "__main__":
Cruncher().run()
Were you able to get this sorted?
I think it works if you use the thread for populating the tree rather than using it for showing the popup. After populating the tree, in the same thread you can close the pop up using Popup.dismiss()
main.py file
from kivy.app import App
from kivy.uix.popup import Popup
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
import time, threading
class popupTestApp(App):
def waitSec(self):
time.sleep(5)
self.p.dismiss()
def popUpFunc(self):
self.p = Popup(title='Test Popup', content=Label(text='This is a test'), size_hint=(None,None), size=(400,400))
self.p.open()
popUpThread = threading.Thread(target=self.waitSec)
popUpThread.start()
if __name__ == '__main__':
popupTestApp().run()
popuptest.kv file
BoxLayout:
BoxLayout:
id:LeftPane
Button:
id:MyButton
text:'Pop it up!'
on_release:app.popUpFunc()
BoxLayout:
id:RightPane
Label:
text: 'Another Pane'
Take a look at the below link where this is explained well.
Building a simple progress bar or loading animation in Kivy
Related
I've been watching some tutorials on Kivy where a functional button prints a string in the console. However I haven't found a simple example where a functional button displays a string somewhere on the GUI (for instance a label) yet. So I tried to make one myself.
Looking for answers here I found some which are far too complex and cover several intertwined issues at the same time, which makes figuring out what would work in a simple example like this daunting, to say the least. Here's what I did so far:
simple.py
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
class SimpleWidget(BoxLayout):
result = ObjectProperty(None)
def button(self, result):
print(str(result.text))
class SupersimpleApp(App):
def build(self):
return SimpleWidget()
if __name__ == "__main__":
SupersimpleApp().run()
And here's supersimple.kv
<SimpleWidget>:
result: result
orientation: 'vertical'
BoxLayout:
id: box1
Label:
text: 'Type something'
TextInput:
id: result
height: 80
Button:
id: button
text: 'Press this'
on_press: root.button(result)
BoxLayout:
id: box2
Label:
id: your_input
What I want to achieve is to show ''result'' in your_input Label instead of printing it.
You can use the ids that you have defined in the kv, like this:
def button(self, result):
print(str(result.text))
self.ids.your_input.text = result.text
I want to clear an MDTextField. The problem is when I set the text to "", the hint_text stays in the wrong position. (It happens when I try to clear while unfocused from the MDTextField)
I tried to focus and then unfocus (from the code) on the text field to fix this, but it's not a good fix because on android the keyboard would come up. I also found this on the KivyMD documentation:
When changing a TextInput property that requires re-drawing, e.g. modifying the text, the updates occur on the next clock cycle and not instantly. This might cause any changes to the TextInput that occur between the modification and the next cycle to be ignored, or to use previous values. For example, after a update to the text, changing the cursor in the same clock frame will move it using the previous text and will likely end up in an incorrect position. The solution is to schedule any updates to occur on the next clock cycle using schedule_once().
Here's the code:
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
kv = Builder.load_string("""
<MainScreen>:
orientation: "vertical"
FloatLayout:
MDTextField:
id: textfield
hint_text: "Text Fields"
pos_hint: {"center_y":.5}
Button:
text: "Clear"
on_press: root.clear_text_field()
""")
class MainScreen(BoxLayout):
def clear_text_field(self):
self.ids.textfield.text = ""
class MainApp(MDApp):
def build(self):
return MainScreen()
if __name__ == "__main__":
app = MainApp()
app.run()
I am trying to develop my first app with kivy but I am experiencing difficulties during development because I am still a beginner and I have no idea how to do it. The goal I have in mind is to create timer plus stopwatch app.
The timer must be very simple with a single button. Pressing the button the first time the timer starts, pressing it the second time it stops.
Later I would like to pass the time recorded with the timer to a stopwatch that puts it in a loop continuously.
For example:
the timer is activated
after 20 seconds I stop it
the stopwatch begins to decrease the value 20 to 0 every second continuously and repeat in a loop.
I tried to have a look around but I can't find anything to lean on. A valid project for the timer is the following
import kivy
from kivy.app import App
kivy.require('1.9.0')
from kivy.lang import Builder
from kivy.properties import NumericProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.clock import Clock
Builder.load_string('''
<MainWidget>:
# Assigning the alignment to buttons
BoxLayout:
orientation: 'vertical'
# Create Button
Button:
text: 'start'
on_press: root.start()
Button:
text: 'stop'
on_press: root.stop()
Button:
text: 'Reset'
on_press: root.number = 0
# Create the Label
Label:
text: str(round(root.number))
text_size: self.size
halign: 'center'
valign: 'middle'
''')
class MainWidget(BoxLayout):
number = NumericProperty()
def __init__(self, **kwargs):
super(MainWidget, self).__init__(**kwargs)
Clock.schedule_interval(self.increment_time, .1)
self.increment_time(0)
def increment_time(self, interval):
self.number += .1
def start(self):
Clock.unschedule(self.increment_time)
Clock.schedule_interval(self.increment_time, .1)
def stop(self):
Clock.unschedule(self.increment_time)
class TimeApp(App):
def build(self):
return MainWidget()
TimeApp().run()
But in any case it has three buttons while I would only like one that acts as both a "start" and a "stop". And I have no idea how to pass the time recorde with timer to the stopwatch.
Please, if there is someone who can help me I would be truly grateful. I don't know who else to turn to and I'm going crazy about this.
Thanks in advance!
P.S.: sorry for my horrible english, i don't speak english and i tried to be as clear as possible
Hello, I am currently creating a GUI using kivy, on Windows. I am using it to ssh into a Raspberry Pi, take an image, then scp it back to my windows machine. I have successfully done this using the GUI. I have two screens. The first is the login. Once I login a second screen appears with buttons and an image. The login screen and buttons serve their functions properly. However, the image file does not update like I want it to. Either I want it to update in a certain interval, or update after I take a picture.
Here is the
Second Screen Interface. I want the picture on the top right to update itself automatically. The "take picture" button takes the picture then sends it to my computer where I'd like to refresh the image in the GUI and display it
My main python file, which I called "ScreenChange2.py" is shown below
import kivy
import os
kivy.require('1.10.0')
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.image import Image
from kivy.properties import StringProperty
from kivy.clock import Clock
from kivy.uix.widget import Widget
from sshtest import ssh #import the ssh class from the ssh python file
class ScreenOne(Screen):
def login(self): #define login using ssh as a function
#Make a Class Variable called connection. This allows for other
#classes to call on it without passing it as an argument
ScreenOne.connection = ssh("192.168.1.3", "pi", "seniordesign")
#ScreenOne.connection.sendCommand("ls")
#ScreenOne.connection.sendCommand("mkdir thisistest")
print("Logging in") #For error checking
def gpioSet(self): #allows for gpio pins to trigger image capture
ScreenOne.connection.sendCommand("echo '18' > /sys/class/gpio/export")
ScreenOne.connection.sendCommand("echo 'out' > /sys/class/gpio/gpio18/direction")
class ScreenTwo(Screen): #This is where all the functions are
def command(self, input): #create a function that sends command through ssh
ScreenOne.connection.sendCommand(input) #Call on connection made before to send command
class MyScreenManager(ScreenManager):
pass
#Create the Application that will change screens. Add App(App) to end of wanted classname
class ScreenChangeApp(App):
#Create a function that builds the app. Keyword self make sures to reference
#current instantiation
def build(self):
screen_manager = ScreenManager()
screen_manager.add_widget(ScreenOne(name = "screen_one"))
screen_manager.add_widget(ScreenTwo(name = "screen_two"))
return screen_manager #after building the screens, return them
#MyScreenManager.login()
sample_app = ScreenChangeApp()
sample_app.run()
The KV file is as shown
#: import os os
<CustomButton#Button>:
font_size: 12
size_hint: .2,.1
<Picture#Image>:
id: image
<ScreenOne>: #define The First Screen
BoxLayout: #Use box layout
Button: #create button
text: "Connect to the Raspberry Pi"
on_press:
root.login()
root.gpioSet()
root.manager.transition.direction= "left"
root.manager.transition.duration = 1
root.manager.current = "screen_two"
<ScreenTwo>:
BoxLayout:
spacing: 10
padding: 10
orientation: "vertical"
CustomButton:
text: "Send an ls command"
on_press:
root.command("ls")
CustomButton:
text: "Take picture"
on_press:
root.command("python cameradaemon.py &") #'&' runs script in background
root.command("sleep .1")
root.command("echo '1' > /sys/class/gpio/gpio18/value") #set pin high to take pic
root.command("echo '0' > /sys/class/gpio/gpio18/value") #take it off to prevent another photo
root.command("scp TEST.jpg Jason#192.168.1.10:C:/Users/Jason/Desktop/RaspberryPiTransferred")
root.command("kill %1")
CustomButton:
text: "Create Histogram"
on_press:
os.system("cd C:/Users/Jason/Desktop/KivyFiles/Histogram & python histogram.py")
AnchorLayout:
anchor_x: 'right'
anchor_y: 'top'
padding: 10
BoxLayout
size_hint: .3, .3
Image:
source: 'C:/Users/Jason/Desktop/RaspberryPiTransferred/TEST.jpg'
As you can probably tell, at the end of the KV file, I insert the image file in a box layout as static. I understand this is why my image won't update, but what I need to know is how I can update it automatically.
I was thinking I could maybe make a custom picture rule, which I started at the top as
<Picture#Image>:
I also understand there is a Reload() function for image files, but I do not understand how to implement that in a KV file.
I've tried creating a class in my main file that runs the reload function every second, but the image doesn't display as it isn't linked to any image in the KV file.
In other words, how do I make it so that the image being displayed in this Second Screen to update automatically given the two scripts I've given. Thank you
In your ScreenTwo class create a StringProperty at the class level:
class ScreenTwo(Screen): #This is where all the functions are
img_src = StringProperty('C:/Users/Jason/Desktop/RaspberryPiTransferred/TEST.jpg')
def command(self, input):
And in your kv file reference it by:
Image:
source: root.img_src
Then change the image just by doing:
img_src = 'some/new/image.jpg'
The image should update without any further actions needed.
I'm learning python and Kivy and I'm really struggling to understand how to call functions and continue functions from a Kivy GUI.
Here is my .py:
import csv
import os
import easygui
import kivy
kivy.require('1.0.7')
from kivy.app import App
from kivy.animation import Animation
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
def csvImport(filename):
with open(filename, 'rb') as f:
reader = csv.reader(f)
your_list = list(reader)
return your_list
class LoadFile(App):
def FileLoadScreen(self):
self.add_widget(Button(size_hint_y=(None), height=('48dp'), text='Select File',
on_press=self.ImportFile))
def ImportFile(self, instance):
filepath = easygui.fileopenbox()
if filepath!='.':
a=csvImport(filepath)
instance.text='File Loaded'
instance.disabled=True
class loginBAKApp(App):
def logAuth(username,password):
if username!='' and password!='':
print('ok')
kv_directory = 'GUI'
if __name__ == '__main__':
loginBAKApp().run()
And this is my loginBAK.kv:
#:kivy 1.9.0
GridLayout:
row_force_default: True
row_default_height: 40
rows: 3
cols: 2
padding: 10
spacing: 10
Label:
id: userLabel
text: 'Username:'
TextInput:
id: username
Label:
id: passwordLabel
text: 'Password:'
TextInput:
id: password
password: True
Button:
id:btn_login
text: 'Login'
on_press: print('OK')
This code seems to work without issues (when I click the login button, it does print 'OK'. I tried to swap it out with
on_press: logAuth(username,password)
and I get an error that logAuth is not defined.
Ultimately, what I'm trying to model here (as my first learning experience) is to hit the login button and as long as the fields are not blank, display a login success message for 5 seconds and then delete the fields and call the LoadFile app (add a button that can be clicked to select and import a file).
What exactly am I doing wrong here? I've sifted through about 60 scripts online and have been looking at the Kivy examples for hours and I cannot figure out how I'm doing this wrong. Can someone point me in the right direction and/or make suggestions as to creating/deleting the gui to do what I described? I'm new to Kivy (and can code basic python scripts) so this is all a little confusing to when I read some of the other questions on stackoverflow.
on_press: logAuth(username,password)
logAuth is a method of your app class, not a function defined in the kv namespace. You can instead use app.logAuth(...), app is a keyword that references the current App instance.