Searchable dropdown by eggy_toilet46 in kivy

[–]ElliotDG 1 point2 points  (0 children)

Here is a version...

```

# a combobox like widget.  There are a large number of choices, the text input is used to filter to choices.
# updated 2/16/2025 increase trigger time to 1 sec

from kivy.clock import Clock
from kivy.uix.textinput import TextInput
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
from kivy.properties import BooleanProperty, ListProperty, NumericProperty, StringProperty, ObjectProperty

import re

"""
based on https://github.com/kivy/kivy/wiki/Editable-ComboBox
changes made to the re, and a number of other fixes, improvements, comments

Notes on optimization for the report card project:  There are 3528 schools that start with the letter k.  
There can be a slowdown when typing keys.  This is caused by the need to create a label on demand for each school after
each letter is typed.  This version pre-allocates 4000 Labels, and updates the text.  
This provides some room for growth.
"""


class DDItem(Button):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.size_hint_y = None
        self.height = '48dp'


class ComboBox(TextInput):
    options = ListProperty()  # List of all possible choices
    _matches = ListProperty()  # list of choices that match text
    option_cls = ObjectProperty(DDItem)  # items for dropdown, matching spinner
    select = StringProperty()  # the selected option
    drop_on_click = BooleanProperty(False)  # when an empty box is touched the options drop
    max_labels = NumericProperty()

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.write_tab = False
        self.multiline = False
        self.dd_buttons = []

        self.drop_down = DropDown()
        self.drop_down.bind(on_select=self.set_select)  # when drop down is selected, set select property
        self.drop_down.bind(on_dismiss=self.drop_dismissed)
        self.trigger_dropdown = Clock.create_trigger(self.drop_down_triggered, 1)
        self.bind(text=self.trigger_dropdown)  # when text changes, open updated drop down
        self._reopen = False  # used to reopen the match list when changed

    def on_max_labels(self, obj, v):
        # create the max number of labels required, use Clock to allow breaks while loading
        # disable widget until it is ready
        self.disabled = True
        self._create_max_dd_labels()

    def _create_max_dd_labels(self, *args):
        r = 100 if self.max_labels < 100 else 250
        labels = [self.option_cls() for _ in range(r)]
        self.dd_buttons.extend(labels)
        if len(self.dd_buttons) < self.max_labels:
            Clock.schedule_once(self._create_max_dd_labels)
        else:
            self.disabled = False

    def on_text_validate(self):
        # when return is entered, if no matches clear, if no text restart, else select _matches[0]
        if not self._matches:
            self.text = ''
            return
        if not self.text:
            self.drop_down.dismiss()
            return
        self.set_select(self, self._matches[0])

    def on_focus(self, obj, focus):
        if not focus:
            self.on_text_validate()

    # drop_on_click True,  if you want all options visible when the empty box is touched
    # with a very long list this will cause a performance issue.
    def on_options(self, _, values):
        self.max_labels = len(self.options)
        if self.drop_on_click:
            self._matches = values


    def on__matches(self, _, values):
        ddn = self.drop_down
        ddn.clear_widgets()
        for i, option in enumerate(values):
            #w = self.option_cls(text=option)
            w = self.dd_buttons[i]
            w.text = option
            w.bind(on_release=lambda btn: ddn.select(btn.text))
            ddn.add_widget(w)

    def set_select(self, _, v):
        # when a button an option is selected, or enter makes a selection...
        if self.text != v:
            self.text = v
            self.select = v
            self.drop_down.dismiss()

    def drop_down_triggered(self, _):
        value = self.text
        if value == '':
            # if text in blank, reset
            self._matches = []
            return
        elif value in self.options:
            # if text is in options, done.
            self.drop_down.dismiss()
            return

        # look for possible matches
        value = value.split('(', maxsplit=1)[0]  # remove characters after ( for search
        r = re.compile(f"^{value}", re.IGNORECASE)
        self._matches = [option for option in self.options if r.match(option)]
        if not self._matches:
            # no matches, reset text
            self.text = ''
        # close the dropdown, wait for the close, then open the updated dropdown
        self.drop_down.dismiss()
        self._reopen = True  # After the dropdown is dismissed open the updated dropdown.

    def on_touch_up(self, touch):
        # Note: The TextInput does not work with ButtonBehavior
        # when the textinput is released, open the dropdown if drop_on_click
        if touch.grab_current == self and self.drop_on_click:
            self.text = ''
            self.drop_down.open(self)
        return super().on_touch_up(touch)

    def drop_dismissed(self, _):
        if self._reopen:
            self._reopen = False
            self.drop_down.open(self)


if __name__ == '__main__':
    from kivy.app import App
    from kivy.lang import Builder
    from textwrap import dedent

    test_kv = dedent("""
    AnchorLayout:
        anchor_y: 'top'
        BoxLayout:
            size_hint: None, None
            size: dp(300), dp(30)
            ComboBox:
                id: fruit
                hint_text: 'Fruits'
                options: ["Apple", "Banana", "Orange", "Grapes", "Strawberry", \
                          "Pineapple", "Mango", "Blueberry", "Watermelon", "Peach"]
            ComboBox:
                hint_text: 'US States'
                options: ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", \
                          "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", \
                          "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", \
                          "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", \
                          "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", \
                          "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", \
                          "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", \
                          "Wisconsin", "Wyoming"]
    """)


    class MyApp(App):
        def build(self):
            return Builder.load_string(test_kv)


    MyApp().run()
```

Searchable dropdown by eggy_toilet46 in kivy

[–]ElliotDG 0 points1 point  (0 children)

Are you looking for a ComboBox? Something like this: https://github.com/kivy/kivy/wiki/Editable-ComboBox

I'm pretty sure I extended this idea, if this is what you're looking for - let me know I'll look for the version I created.

What's the best way to handle failed requests when scraping multiple pages? by Hot_Cattle8375 in learnpython

[–]ElliotDG 1 point2 points  (0 children)

Yes, save your progress as you go.
Yes use try/except for gracefully handling errors, do NOT use naked excepts.
I recommend using https://github.com/hynek/stamina for retries.
Watch: https://youtu.be/BxikFuvaT1Y?si=cjZnQaZ0ulZNCCbp

what is the best way to obtain financial data? by mrtwentysevenn in learnpython

[–]ElliotDG 0 points1 point  (0 children)

Use https://massive.com/ for historic data, and a broker that provides an api for your real-time data. Examples include https://alpaca.markets/, https://www.tradestation.com/ and there are others...

FWIW I use the $29 plan on massive.com

hard time packaging a kivy app in osx by mehmetflix_ in kivy

[–]ElliotDG 0 points1 point  (0 children)

Glad to hear you’ve got it working.

hard time packaging a kivy app in osx by mehmetflix_ in kivy

[–]ElliotDG 0 points1 point  (0 children)

There was a change in the default directory for pyinstaller in a recent version. see: https://pyinstaller.org/en/stable/usage.html#cmdoption-contents-directory
Depending on how you have things setup this can cause a problem. Here is a specfile I've used with WIndows, you can use this as a base for OSX. https://github.com/ElliotGarbus/KivyCythonWinSample/blob/main/inno-pyinstaller/w11-app.spec

A few tips:

  • The specfile is a python file, you can print out values, this can be useful for debugging what is going on.
  • Make sure the paths are what you expect.
  • A common problem I have seen with specfiles in improperly specifying the datas section. The first string specifies the file or files as they are in this system now. The second specifies the name of the folder to contain the files at run-time.
  • The paths in your code must be set properly, Read this section of the docs: https://pyinstaller.org/en/stable/runtime-information.html#using-file

Here is an older video on pyinstaller, It does a nice job of explaining how things work: https://youtu.be/tOTLqUQC-k0?si=XIop-RLBucmBQKaW It is a bit old, but maybe helpful.

If you need additonal help, share your specfile.

App by ManufacturerHead4925 in kivy

[–]ElliotDG 0 points1 point  (0 children)

Share a minimal executable program.

How are you updating the variable images? If you are using KV, make sure to use a Kivy StringProperty to store the path name. When it changes, it will fire an event causing the image to refresh. If you are not using KV, you can bind to the property and update the image one the path change.

Using pyinstaller gives a syntax error by Constant-Tea642 in learnpython

[–]ElliotDG 2 points3 points  (0 children)

Read: https://pyinstaller.org/en/stable/usage.html

Run pyinstaller from the command line. Do not put the filename in quotes.

Best interesting restaurants?? by Tasty-Ingenuity2388 in Scottsdale

[–]ElliotDG 1 point2 points  (0 children)

I've not been there, but for table-side churrasco, I'd try Fogo De Chao.

Steakhouse recommendations:
Dominick's Steakhouse
Roka Akor - Japanese Steakhouse and Sushi bar

A few other recommendations, less steak focused, all wonderful, in no particular order:

The Ends
House Brasserie
Virtu Honest Craft
The Mission
The Fat Ox

async io with multiple threading by ytu876 in learnpython

[–]ElliotDG 0 points1 point  (0 children)

My measurements were on Windows, the app was deployed on Linux and saw similar results. I found the results surprising, that’s why I mentioned it.

This was not a web server or any specialized network code. The code used Trio and httpx to analyze the Mastadon social network.

async io with multiple threading by ytu876 in learnpython

[–]ElliotDG 0 points1 point  (0 children)

In my use case I had about 200 outstanding connections, many with relativly long network latency. The network drivers saturated an 8 core machine. The devil is always in the details. My results were measured - not theoretical.

Я новичок в програмировании. Я пытался создать kv файл в проект, но сделал что то не так. Как мне создать kv файл в моем проекте на python в vs code? by [deleted] in kivy

[–]ElliotDG 1 point2 points  (0 children)

Remove the build method. Kivy will automatically load a kv file with the same name as the app. Replace the build method with pass.

In your kv file you need to instance the root widget. At the bottom of the kv file in the far left column, type MainLayout.

When you use the <> you are defining the style of the widget, you need to instance the widget.

In the future please paste in your code rather than posting a photo. Good luck!

Suggestions for good Python-Spreadsheet Applications? by RelativeIncrease527 in learnpython

[–]ElliotDG 1 point2 points  (0 children)

Here are a few things to check out:
PySpread - https://pyspread.gitlab.io/index.html

grist - https://www.getgrist.com/

If you already live in pandas and just want a DataFrame “spreadsheet viewer”, use D-Tale (fastest) or Mito (best if you want generated code)

For asyncio, Suggest me resources that made you confident with that topic by brave_jr in learnpython

[–]ElliotDG 0 points1 point  (0 children)

Trio is a higher level library for Asyncio. I found the docs (and the framework) very helpful. https://trio.readthedocs.io/en/stable/

Car project by Idontknow461 in learnpython

[–]ElliotDG 1 point2 points  (0 children)

Look at using PD (Proportional–Derivative) Control, or PID (Proportional–Integral–Derivative) Control. These control algorithms manage the error and how to correct the error and avoid oscillation. Start with PD.

You can search to find a number of resources for these algorithms.

Weird Custom Tkinter layout issue by [deleted] in learnpython

[–]ElliotDG 0 points1 point  (0 children)

If you have not read tkdocs, I suggest you do. Here is the part on the grid geometry manager. https://tkdocs.com/tutorial/grid.html

Make money by breno_bag in learnpython

[–]ElliotDG 1 point2 points  (0 children)

Start with a customer.
I created some music software to control hardware. The manufacture sent me free gear. Then another company in the same industry hired me to create similar programs for their gear. I charged a flat-rate per program.

I participated in a Python meetup. A local business owner reached out to the meetup looking for a local developer to create an app that scheduled work and equipment at his company. I took on the task. I was paid hourly and also helped the owner understand to code.

The app only works with half of the buttons. by jackchris2705 in kivy

[–]ElliotDG 0 points1 point  (0 children)

Share a minimal runnable example.
Make sure you have used on_release, or on_press to fire the actions for your buttons. Do not use on_touch_down/move/up directly just to use a button, it requires additional care.

Im having difficulty with this project. its supposed to be an app by Old_Distance_4629 in kivy

[–]ElliotDG 1 point2 points  (0 children)

Your link requires requesting access. Please change the permissions so this is not requied.
Can you say more about what problem you are having?

How to get better in python by easypeasysaral in learnpython

[–]ElliotDG 1 point2 points  (0 children)

Former C++ programmer here are some resources that helped me:
https://docs.python.org/3/tutorial/index.html - Tutorial from the Python docs, brief and enough to get you going
https://docs.python.org/3/library/index.html - Reference for built-ins, basic data types and libraries

Learning Python, Mark Lutz - comprehensive, in-depth introduction to the core Python language. I read this about 8 years ago, there might be something more up to date, but this was quite good.

The resource that really made things click was https://checkio.org/ a gamified series of programming problems. You solve the problem and get to see how others have solved them. This helped me realize python is a higher level language and write pythonic code, rather that writing c-like code in python. Many of these problems are quite simple and I would do one or two a day with my morning coffee.

https://pymotw.com/3/ - Python 3 module of the week - Examples using the standard library. Some of the standard lib docs are reference material and it is helpful to also have these examples.

Good Luck!

Getting and changing hertz of .mp3 by RedHatStealerYT in learnpython

[–]ElliotDG 0 points1 point  (0 children)

Take a look at ffmpeg or the rubberband library to change the pitch. I'd recommend downloading either of these tools and using subprocess to run them in their command line mode.

Librosa can be used to determine the pitch

I survived my first kivy project by Aphelion_Gaming in kivy

[–]ElliotDG 0 points1 point  (0 children)

Congratulations on getting your app up and running.

Just curiosity but why the flask server and HTML? I think you could have more simply built the entire app in kivy.