Kivy:将函数变量应用于按钮文本

Kivy : Apply function variables to Button Text

我得到了一些滚动可用的屏幕示例。 我正在测试这个例子以适用于我的应用程序。

当我启动这个 python 文件时,我可以看到如下所示的屏幕

但我想要的是上面这样的。 我想制作与 numberoflist 一样多的按钮 并把三行TESTTEST.txt放在一个按钮里如上图

6, 2, 159, 6, 6, 467 每个数字都是 Businfo 的列表 所以我可以访问每个数字作为 businfolist[0]businfolist[1]businfolist[2] 等等..

所以首先,我为了测试编写了这样的代码。

    BoxLayout:
        orientation: 'vertical'
        size_hint: 1, 0.35
        padding: 0
on_parent:
    for i in range(root.numberoflist): txt = root.businfolist[i]; self.add_widget(Button(text= txt, id=txt))

但是没用。这是回溯

 Traceback (most recent call last):
   File "t2.py", line 65, in <module>
     presentation = Builder.load_file("t2.kv")
   File "/usr/local/lib/python2.7/dist-packages/kivy/lang/builder.py", line 301, in load_file
     return self.load_string(data, **kwargs)
   File "/usr/local/lib/python2.7/dist-packages/kivy/lang/builder.py", line 368, in load_string
     parser = Parser(content=string, filename=fn)
   File "/usr/local/lib/python2.7/dist-packages/kivy/lang/parser.py", line 392, in __init__
     self.parse(content)
   File "/usr/local/lib/python2.7/dist-packages/kivy/lang/parser.py", line 501, in parse
     objects, remaining_lines = self.parse_level(0, lines)
   File "/usr/local/lib/python2.7/dist-packages/kivy/lang/parser.py", line 605, in parse_level
     level + 1, lines[i:], spaces)
   File "/usr/local/lib/python2.7/dist-packages/kivy/lang/parser.py", line 605, in parse_level
     level + 1, lines[i:], spaces)
   File "/usr/local/lib/python2.7/dist-packages/kivy/lang/parser.py", line 615, in parse_level
     'Invalid property name')
 kivy.lang.parser.ParserException: Parser: File "/root/Desktop/hi/t2.kv", line 54:
 ...
      52:                padding: 0
      53:       on_parent:
 >>   54:           for i in range(root.lenbil): txt = root.businfolist[i]; self.add_widget(Button(text= txt, id=txt))
      55:
      56:<MyButton@Button>:
 ...
 Invalid property name

而且我想到了@Button里面放变量,那要不要用global呢? 我不知道。 感谢您阅读。我期待着回答。

t2.py

#-*- coding: utf-8 -*-
__version__ = "1.0"

import kivy
import os
kivy.require('1.10.0')
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.image import Image
from kivy.uix.label import Label
from kivy.animation import Animation
from kivy.clock import Clock
#from kivy.config import Config #windows size fixed
#Config.set('graphics', 'resizable', 0)
from kivy.core.window import Window 
Window.size = (540, 960)
#Window.size = (1080, 1920) 
##########FOR BUS INFORMATION UPDATE#############
from urllib import urlencode, quote_plus
from urllib2 import Request as RQ
from urllib2 import urlopen as UO
import urllib
import xml.etree.ElementTree as etree
import os
import datetime


def oopath(ndid, uor):
    path = os.path.join(ndid + '.txt')
    return path

##############################################################################################################

class StationTest(Screen):

    def __init__(self, **kwargs):
        super(StationTest, self).__init__(**kwargs)

    oo = oopath('TESTTEST', 0) #path to nodeidlist, ('nodeid', uor) -->> if uor == 0 >> path to ubuntu
    self.rpandgv(oo)

    def rpandgv(self,path): 
    with open(path) as businfo:
        Businfo= [] 
        nolinenum=businfo.readline()
        while nolinenum!='': 
        Businfo.append(nolinenum)
        leftstations = (businfo.readline().rstrip('\n') + ' stations'.rstrip('\n'))
        lefttime = (businfo.readline().rstrip('\n') + ' seconds'.rstrip('\n'))
        nolinenum = businfo.readline().rstrip('\n')
        Businfo.append(leftstations)
        Businfo.append(lefttime)
        self.businfolist = Businfo
        self.lenbil = int(len(Businfo))
        self.numberoflist = int(len(Businfo)/3)


class ScreenManagement(ScreenManager):
    pass

presentation = Builder.load_file("t2.kv")

class Test2App(App):
    def build(self):
        return presentation


Test2App().run()

t2.kv

# -*- coding: utf-8 -*-
#:import NoTransition kivy.uix.screenmanager.NoTransition
#:import SlideTransition kivy.uix.screenmanager.SlideTransition
#:import Label kivy.uix.button.Label

ScreenManagement:
    transition: SlideTransition(direction='left')
    StationTest:

<StationTest>: 
    name: 'StationTest'
    canvas:
        Rectangle:
            pos: self.pos
            size: self.size 
            source: 'image/background.png' #backgroundimage
    header: _header
    ScrollView:
        FloatLayout:
            size_hint_y: None
            height: 500
            BoxLayout:
                id: _header
                orientation: 'vertical'
                size_hint: 1, 0.10
                pos_hint: {'top': 1.0}
                anchor: _anchor
                canvas:
                    Color:              
                        rgba: 0.8, 0.6, 0.4, 1.0
                    Rectangle:
                        pos: self.pos
                        size: self.size
                Label:
                    text: "STATION > STATION"
                    font_size: 40
                BoxLayout
                    id: _anchor
                    size_hint_y: 0.3
                    canvas.before:
                        Color:              
                            rgba: 0.3, 0.5, 0.8, 1.0
                        Rectangle:
                            pos: self.pos
                            size: self.size
                    Label:
                        text: "TEST1234"

            BoxLayout:
                orientation: 'vertical'
                size_hint: 1, 0.35
                padding: 0
                MyButton:
                MyButton:

<MyButton@Button>:
    text: "contents (%s)"%('123')

    background_color: (255, 255, 255,0.8)

TESTTEST.txt

6
2
159
6
6
467
6-1
12
832
6-1
3
189
8
8
515
35
4
317
112
10
765
112
2
107
780
30
3067
909
13
1665

您的代码还有一些其他问题(一旦您显示按钮,您就会发现)和 post 中的一些缩进错误。但是添加这些按钮的一种简单方法是在 StationTest.__init__():

中添加一行
Clock.schedule_once(partial(self.rpandgv, oo))

代替行:

self.rpandgv(oo)

Clock.schedule_once 确保代码仅在更新显示并填写 .ids 字典后才为 运行。在 rpandgv() 方法的末尾,添加添加按钮的代码:

    for i in range(self.lenbil):
        txt = self.businfolist[i]
        self.ids.buttons.add_widget(Button(text=txt, id=txt))

此外,添加:

id: buttons

BoxLayoutkv 声明,我相信你想在其中添加按钮(带有两个 MyButton 声明的按钮)。