Forum Archive

Help for widget

crazy666

Hello i try to lean python and i have difficulty for create widget ,

import console
import clipboard
import ui
import appex, ui
mv = ui.View(frame=(0,0,320,420))
mv.background_color = 'black'
def num_inp(sender):
    if sender.title == 'next':
        sender.active = 1 + sender.active
        return
    tf_idx = sender.superview['nf'].active
    tf = sender.superview[['brut','long','nb'][tf_idx]]
    tf.text += sender.title
l1 = ui.Label()
l1.text = 'brut:'
l1.frame = (67,2,50,20)
l1.text_color = '#ffffff'
mv.add_subview(l1)
l2 = ui.Label()
l2.text = 'long:'
l2.frame = (65,25,50,20)
l2.text_color = '#ffffff'
mv.add_subview(l2)
l3 = ui.Label()
l3.text = 'nb:'
l3.frame = (77,48,50,20)
l3.text_color = '#ffffff'
mv.add_subview(l3)
l4 = ui.Label()
l4.text ='palette:'
l4.frame = (67,71,110,20)
l4.text_color = '#ffffff'
mv.add_subview(l4)
l5 = ui.Label()
l5.text = 'rouleau:'
l5.frame = (64,94,110,20)
l5.text_color = '#ffffff'
mv.add_subview(l5)
t1 = ui.TextField(name='brut')
t1.frame = (105,2,70,20)
mv.add_subview(t1)
t2 = ui.TextField(name='long')
t2.frame = (105,25,70,20)
mv.add_subview(t2)
t3 = ui.TextField(name='nb')
t3.frame = (105,48,70,20)
mv.add_subview(t3)


for i in range(0,5):
    b = ui.Button()
    b.action = num_inp
    b.title = str(i)
    b.frame = (180+i*40,0,54,50)
    b.font = ("<system>",36) 
    b.background_color = '#949494'
    mv.add_subview(b)
for j in range(5,10):
    b = ui.Button()
    b.action = num_inp
    b.title = str(j)
    b.frame = (-20+j*40,50,54,50)
    b.font = ("<system>",36)
    b.background_color = '#949494'
    mv.add_subview(b)
nf =ui.Button(name='nf')
nf.title = 'next'
nf.font = ("<system>",20)
nf.background_color ='#c5c5c5'
nf.action = num_inp
nf.active = 0
nf.frame = (5,5,50,30)
mv.add_subview(nf)

appex.set_widget_view(mv)
crazy666

Sorry for my english
I try to create widget with my code

brut = int(input('brut:'))
long = int(input('longueur core:'))
nb = int(input('nb roll:'))
skc = 73 #skid canadien#
skus = 60 #skid usa#
tub6 = 0.42 #core de 6 pouce#
tub3 = 0,10 #core de 3 pouce#
pall = brut - skc - long * tub6 * nb
roll = pall / nb
print('rouleau:' , roll, 'lbs')
print('pallette:' , pall, 'lbs')
And i try to integrate 2 switch for (skc/skus) and (tub6/tub3)
stephen

@crazy666 can you do us a favor nd pleade put ``` (three backnticks) before and after your code so it preserves _ and spacing?

stephen

@crazy666

to start what are you trying to do with your widget? from what i see itsv bunch of buttons but code fails in last two 4 loops. what are we doing with i40 and j40? shoulf it be b.frame = ((180+i)40,0,54,50)

mikael

@crazy666, as @stephen said, hard to read or understand the code without formatting.

Are you using active where it should be enabled?

crazy666

Thank for help stephan ,becose i don't know how split number

mikael

@crazy666 said:

tf.text += sender.title

This looks like it will result in: ”1” + ”2” = ”12”

Is that intended? Or are you expecting ”3”? In which case you need:

tf.text = str(int(tf.text) + int(sender.title))
mikael

@crazy666, now that it is formatted, I see that both of my earlier comments might be irrelevant.

What is not working?

mikael

@crazy666, probably a typo for tub3 makes it a tuple instead of a decimal number.

crazy666

Thanks @mikael i want create

https://imgur.com/W1oSZmS
With my calcul in my widget home page

stephen

@crazy666 no problem. checkout this page on markdown syntax very easy to learn and kinda fun i find.

this is what the ``` comes from..

that aside..

you could of used:
- b.frame = ((180+i)40 ,0,54,50)
- b.frame = (180+i*40,0,54,50)

difference here is first case will do 180+i=value then Rect.x=value*40 Rect being frame. * is Multiplication..

  • second case will do oposit i*40=value then* Rect.x=180+value

EDIT

i see now that my page cought up u got this. Thank you @mikael

crazy666

@stephen hooo nice

stephen

@crazy666 said:

  • we need to check if the active TextView is last then start over or exit sequince choices. i get Seq out of range on 4th press

  • posibly add a check to see if expected data was givin.

  • if ⇑ is true, deactivate next and display calc or get_value to finish the problem.

is this the problem you are facing?

this will fix list outbof range:



def num_inp(sender):
    if sender.title == 'next':
        sender.active = (1 + sender.active) if (1 + sender.active) <= 2 else 0
        return

crazy666

@stephen said:

is this the problem you are facing?

Yes , you are a genius !!!
1 week I search on google for that

stephen

@crazy666

see update to mynlast post

crazy666

I'm trying to understand how "rect" works ,wait please
,speak french?

stephen

@crazy666 donne-moi juste une minute pour te donner des infos

stephen

@crazy666 J'espère que c'est lisible. utilisation du traducteur..

Rect provient du module scene. vous pouvez également utiliser le module ui via

from scene import * # importe tout à partir du module scene

v= ui.View() # ui est appelé et utilisé dans la scene pour que nous l'utilisions parce que nous avons appelé 'import *' sur place

From Pythonista Doc Scene.Rect(x, y, w, h)

scene de classe.Rect(x, y, w, h)
La classe Rect est utilisée pour les zones de délimitation et d'autres valeurs de rectangle, par exemple l'attribut Node.frame. Un rectangle est représenté par (x, y, w[idth], h[huit]), avec (x, y) comme son coin inférieur gauche.

Dans la plupart des cas, Rect se comporte comme une séquence, semblable à un 4-tuple. Par exemple, vous pouvez également accéder à son composant x en utilisant la notation d'indice (r[0]). Les rectangles supportent également l'itération, le déballage des arguments, etc.

Chaque fois qu'un objet Rect est utilisé comme attribut dans le module scene, vous pouvez fournir une séquence de 4 nombres (par exemple une liste ou un tuple).

Rect.x
Composant x du coin inférieur gauche du rectangle.

Rect.y
La composante y du coin inférieur gauche du rectangle.

Rect.w
Rect.width
Largeur du rectangle.

Rect.h
Rect.height
La hauteur du rectangle.

Rect.origine
Équivalent à Point(rect.x, rect.y)

Rect.size
Équivalent à Size (rect.w, rect.h)

Rect.min_x
Équivalent à min(rect.x, rect.x + rect.w) (composant x du bord gauche)

Rect.max_x
Équivalent à max(rect.x, rect.x + rect.w) (composant x du bord droit)

Rect.min_y
Équivalent à min(rect.y, rect.y + rect.h) (composant y du bord inférieur)

Rect.max_y
Équivalent à max(rect.y, rect.y + rect.h) (composant y du bord supérieur)

Rect.center([p])
Lorsqu'il est appelé sans arguments, renvoyez le centre du rectangle. Lorsqu’un point est passé en argument, les valeurs x et y du rectangle sont ajustées, de sorte que le nouveau centre du rectangle est p.

Rect.Contient_point(p)
Renvoie True si le point donné se trouve dans les limites du rectangle, False dans le cas contraire.

Rect.Contient_rect(other_rect)
Renvoie True si le rectangle donné se trouve entièrement dans les limites de ce rectangle, False dans le cas contraire.

Rect.intersects(autre_rect)
Renvoie True si ce rectangle se croise avec l'autre rectangle, False dans le cas contraire.

Rect.intersection(other_rect)
Retourne un Rect qui correspond à l'intersection de ce rectangle avec l'autre.

Rect.union(autre_rect)
Retourne le plus petit Rect qui contient les deux rectangles.

Rect.translation(x, y)
Équivalent de Rect(r.x + x, r.y + y, r.w, r.h)

Rect.inset(haut, gauche[, bas, droite])
Retourne un rectangle ajusté par les entrées d'arête données. inférieur/droit sont optionnels et par défaut, la valeur est la même que supérieure/gauche.

crazy666

Sa fait un mois que j'apprends python
J'ai lu au complet sur python.org et lu un livre en anglais mais j'ai de la difficulté en anglais .j'essais d'apprendre l'anglais en meme temps 😂
Et se que je trouve difficile c'est que sur internet il parle seulement de tinker et sur ios il ne la pas

stephen

à peu près Rect est un carré sur l'écran en points avec Taille w, h donc ceci:

from scene import *

w, h=get_screen_size()
box1 = Rect(w/2-50, h/2-50, 100, 100)

box1 sera un rectangle de 100x100 placé au centre de l'écran.

crazy666

It work in widget?

stephen

@crazy666 Ce forum est vraiment le seul site qui vous aidera pleinement avec Pythonista


in ui module Rect est destiné aux objets Path. nous voulons nous en tenir à frame and bounds in notre cas.

mais si vous aimez jouer avec la scène et utiliserLableNode, SpriteNode and découvrez Eventnloop de Scène. dans votre cas, cela n' a pas vraiment d' importance.

vous pouvez juste finir avec l'assurance-chômage puisque vous en êtes presque un. Je travaille sur un modèle de jeu RPG qui aidera les nouveaux utilisateurs à mieux comprendre les capacités de la scène.

ma suggestion ici, cependant, est d' ajouter la déclaration composée que j' ai faite plus tôt.
puis ajouter un bouton pour calculer pour la résolution .
enfin afficher la résolution.

stephen

@crazy666 French Python Docs

crazy666

Ok I come back.
I go work on my script
Thanks

stephen

@crazy666 Encore une chose, si vous utilisez Google Chrome vous pouvez aller à ce lien et utiliser construit dans translater pour lire des documents en français

stephen

Bonne chance ! nous sommes ici si vous avez des problèmes. mais s'il vous plaît donner que vous êtes nouveau à la fois python et pythonidta toujours vérifier les documents et les postes de recherche avant de poster. dans un premier temps, la plupart des problèmes auront déjà une solution d'un autre problème 🙃 voyages heureux

crazy666

No i want learn english to

cvp

@crazy666 Hello, welcome here.

I'm also French speaking and my English is not good at all but I try to always write here in English, surely with a lot of errors.
@stephen has been very kind to translate all his advices in French but, personally, I think we should all write in English here. For this reason: if somebody meets the same problem as you, he would never find in this forum the right topics if everybody writes in his/her own language.
And to understand the topic, each user would need to translate it, instead of only one person, you for instance who could translate his questions and their answers to/from English.
That's really not an attack, only my opinion.
For info, it happens that I also need to translate some words from English to French, and I use Google Translate or select/popup menu/definition if you have defined English and French as languages.

cvp

@crazy666 And I want to add that all your first posts, in English, were very good and understandable.
Good luck with Python and this marvelous Pythonista app with a forum full of incredible guys/girls.

stephen

@crazy666 outstanding ill be on for w few hours if u need any further help. @mikael @ccc @JonB @cvp and many more are wonderfull in assisting in different areas pythonista's lib. looking forward to see what all you come up with!

banner

stephen

@cvp i agree i just like to help however i can 😊

cvp

@stephen I understand and I also want to help others, if I can.
It was not a criticism of your kind help and effort, it was only my personal opinion and I don't want to ask other people to share my opinion, sincerely. I would even be happy to help in French if no other way exists.

stephen

@cvp

I do agree on just observing english 🙃 and i myself observed Zero negative intention in your coment. just logic and care for community. well im off to try and get this event system structure going.. lol

mikael

@crazy666, just for fun, here’s the ”almost standard” way of wrapping a number range from 0 to (how_many-1):

i = (i+1) % how_many
crazy666

Wait i work on 😉

crazy666

@cvp i understand ,it logic

crazy666

Hello i have a question ...
what is the difference between frame and scene?
i'm desperate i don't know how to restart
What is the best to start ?
Create view class and after add fonction?
Or what is the best strategy for write

I don't want use ui editor becose i want understand structure

Thanks for help me !!

cvp

@crazy666 Hello, I understand that it is not easy to start because the app provides so much functionalities.
Do you know the local help of Pythonista by selecting a word?
This displays a little popup menu where you can tap help and you will get the local help of the module or method or function....

stephen

@crazy666 said:

Hello i have a question ...
what is the difference between frame and scene?
i'm desperate i don't know how to restart
What is the best to start ?
Create view class and after add fonction?
Or what is the best strategy for write

I don't want use ui editor becose i want understand structure

Thanks for help me !!

frame

in the instance of ui module is a Rect that we talked about last time and if i understand correctly, does some initial calculation when object is created.
- x
- y
- width
- hieght
- bounds
so on..

scene

This is a complete, actually a chain of, modules for bridging Pythonista with SceneKit from Apple. it has many connections with the ui module. the class Scene that your MyScene class dirives from is itself a sub-class of SceneView from ui. with this said you can alternativle write a ui project and make one View element sub-class SceneView and write a MyScene class then set your MySceneView.scene = MyScene() and this allows you to present your scene in your ui other than forcing fullscreen.

so for this part,

frame is an attribute of ui.View (scene nodes you generally set the Node.position and Node.size. position being a Point object and size a Size object. i belive even if you pass a normal 2tuple scene should convert to object needed but i find its much cleaner and good practice to just explucitly instance the object.
hint: MySprite.position = MyScene.size/2 willconvert the Size object to Point object while setting sprite to center of screen 😉🤓

scene is a module for animations and Game Development. not limited to though.. see here for documentation on scene module.

---

I personally suggest you learn scene then continue with ui while using SceneView. but its really up to whats comfortable for you buddy..

my typical path i take is similar to following for starting scene projects...
-import my standart modules..

inside a core.py i place all my imports. including my from scene import *.
- wrighy out mt factory functions..
functions that creat my nodes and other objects. this helps maintain consistency and reduce programer error from typos.. ⤹⤹⤹

example...

    #explicitly i pass Point and Size objects..
    #leave out size for LabelNode to allow autosizeing ⤶
    #to font and string sizes..
    def new_label(text=None, point=None, size=None, 
                    parent=None, font=('Helvetica', 16)):
        label = scene.LabelNode(
            text=text,
            font=font,
            position=point, 
            size=size,
            parent=parent,
            anchor_point=(0.5, 0.5)
        )

        # ... add logic for creating all labels ...
        return label


    now inside main script...
    from core import *
    w, h = get_screen_size()

    class MyScene(Scene):
        def __setup__(self, *args, **kwargs):
            self.score = 0
            self.score_display = new_label(self.score, 
                        Point(w/2, h-50), Size(150, 45), self)

*note: im using scene from core.py instead of importing in both.. this allows me to creat scene objects in core.py without doing from scene import ... for everything i use. if both scripts core and main did from scene import * the interpreter will not import core.py. with message cannot import core.

  • from here sky is the limit!

i hope this helps you in what you needed

Also..

using UI Builder wont effect your path in learning structure. it only give a visual interactive way to set up the ui. you can still programatically set properties and have a custom view class..

roku_one

I tried to use the same screen widget for many porpuse. And it work. It just a shame that put a button also depends of the lengh of the text inside

crazy666

@cvp i swipe left and i use "?" For search description

cvp

@crazy666 that's the right way to access total local help and a search on it

crazy666

Thanks you @cvp

cvp

@crazy666 But don't forget Pythonista offers also the possibility to use the
select / popup menu / help like showed some posts above

crazy666

@cvp yes !!!now i will use it 😉

stephen

@roku_one said:

I tried to use the same screen widget for many porpuse. And it work. It just a shame that put a button also depends of the lengh of the text inside

im not sure i understand? are you saying the button wont fit the text or he size is clampig to string size?

what is your use senario?

mikael

@stephen, it’s spam.

stephen

@mikael

wonderful lol

cvp

@mikael Sure? He had also created this topic

mikael

@cvp, I was pretty sure, given ”1 post” and the content, until I saw the other post. My apologies @roku_one.