来自kivy蓝图的Python-kivy代码

2024-09-30 01:31:18 发布

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

我试着按照马克·瓦西尔科夫的书《基维蓝图》来做。在第21页,他介绍了一个更新标签文本的函数。你知道吗

项目文件夹中有两个文件(请参见下面的代码)。在类ClockApp中定义了函数update_time(self, nap)。我将intellijidea社区与python插件一起使用,集成开发环境(IDE)告诉我nap是一个未使用的参数。如果我删除nap作为参数,我会得到一个错误update_time() takes 1 positional argument but 2 were given。我怎样才能去掉这个伪参数?你知道吗

# Source: Chapter 1 of Kivy Blueprints
# File: main.py
from time import strftime

from kivy.app import App
from kivy.clock import Clock
from kivy.core.window import Window
from kivy.utils import get_color_from_hex


Window.clearcolor = get_color_from_hex("#101216")
# from kivy.core.text import LabelBase


class ClockApp(App):

    def update_time(self, nap):

        self.root.ids.time.text = strftime("[b]%H[/b]:%M:%S")

    def on_start(self):
        Clock.schedule_interval(self.update_time, 1)


if __name__ == "__main__":
    ClockApp().run()

另外还有一个时钟.kv文件

# File: clock.kv
BoxLayout:
    orientation: "vertical"
    Label:
        id: time
        text: "[b]00[/b]:00:00"
        font_name: "Roboto"
        font_size: 60
        markup: True

Tags: 文件函数textfromimportself参数time
1条回答
网友
1楼 · 发布于 2024-09-30 01:31:18

绑定总是传递额外的信息,例如在本例中,它向我们发送调用函数的确切时间段。如果不想使用它,可以使用lambda方法:

class ClockApp(App):
    def update_time(self):
        self.root.ids.time.text = strftime("[b]%H[/b]:%M:%S")

    def on_start(self):
        Clock.schedule_interval(lambda *args: self.update_time(), 1)

如果您只想消除警告:“unused parameter”,您可以使用_

class ClockApp(App):
    def update_time(self, _):
        self.root.ids.time.text = strftime("[b]%H[/b]:%M:%S")

    def on_start(self):
        Clock.schedule_interval(self.update_time, 1)

相关问题 更多 >

    热门问题