如何在每次按下按钮时从列表中随机生成新项目?

2022-09-28 20:08:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习如何使用kivy,我制作了一个示例代码,每次按下一个按钮时都可以从列表中选择一个新的随机项。当我运行这段代码时,我得到一个错误:“第19行,在NewChoice中 number+=1 UnboundLocalError:赋值前引用的局部变量“number”。如何在NewChoice函数中引用数字

代码:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.uix.screenmanager import Screen
import random

RandomList = ["First", "Second", "Third", "Fourth", "Fifth"]
number = 0

class GameScreen(Screen):

    def __init__(self, **args):
        Screen.__init__(self, **args)
        self.item = random.sample(RandomList, 5)
        self.label = Label(text=str(self.item[number]), color=(1,0,0,1), font_size=(45),size_hint=(0.2,0.1), pos_hint={"center_x":0.5, "center_y":0.9})
        self.add_widget(self.label)

    def NewChoice(self):
        number += 1
        self.label.text = str(self.item[number])

Builder.load_string('''
<GameScreen>:
    name: "GameScreen"
    canvas:
        Color:
            rgb: 1, 1, 1
        Rectangle:
            pos: self.pos
            size: self.size

    Button:
        size: self.texture_size
        on_release: root.NewChoice()
        text: "Press"
        font_size: 50
        color: 1,1,1,1
        background_color: (0,0,0,1)
        background_normal: ""
        background_down: ""
        size_hint: None, None
        pos_hint: {"center_x":0.5, "center_y":0.6}
        width: self.texture_size[0] + dp(10)
        height: self.texture_size[1] + dp(10)
    ''')

class TestApp(App):
    def build(self):
        return GameScreen()

if __name__ == '__main__':
    TestApp().run()

Tags: 代码fromposimportselfnumbersizedefscreenlabelcenterkivyhintgamescreennewchoice