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

时间:2018-08-23 03:50:18

标签: python kivy kivy-language

我有一些滚动可用的屏幕示例。 我正在测试该示例以应用于我的应用程序。

当我启动此python文件时,我可以得到如下所示的屏幕

enter image description here

enter image description here

但是我想要的是这样的。 我想制作多达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中,那么我应该使用全局变量吗? 我不知道。 感谢您的阅读。我期待着回答。

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

1 个答案:

答案 0 :(得分:1)

您的代码还有其他一些问题(一旦显示“按钮”,您将发现这些问题)以及帖子中的某些缩进错误。但是添加这些按钮的一种简单方法是在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

kv的{​​{1}}声明中,我相信您要在其中添加按钮(带有两个BoxLayout声明的按钮)。