且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Kivy for Python 中按下按钮时更新标签的文本

更新时间:2023-10-07 09:12:46

好吧!您的代码确实需要改进.(我理解你没有经验.)

Well! there was a real need for improvement in your code. (I understand it as you are not experienced.)

改进:1

如果您在 build() 上返回一个小部件,或者您设置self.root.(你不应该在构建函数本身中制作所有的 gui.)

An application can be built if you return a widget on build(), or if you set self.root.(You shouldn't make all of the gui in build function itself.)

def build(self):
    return Hello() #That's what is done here

改进:2

on_release/on_press 两者总是有用的.

on_release/on_press both are always useful.

self.help_button = Button(text = "Help", size_hint=(.3, .1),pos_hint={'x':.65, 'y':.1},on_press = self.update)

改进:3

当 help_button 被按下时,更新函数被调用来改变 main_label 的文本.

As help_button is pressed, update function is called which changes the text of main_label.

def update(self,event):
    self.main_label.text = "Changed to change"

这是完整改进的代码

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.floatlayout import FloatLayout
from kivy.clock import Clock

energy = 100
hours = 4

class Hello(FloatLayout):
    def __init__(self,**kwargs):
        super(Hello,self).__init__(**kwargs)

        self.energy_label = Label(text = "Energy = " + str(energy), size_hint=(.1, .15),pos_hint={'x':.05, 'y':.9})
        self.time_label = Label(text = "Hours = " + str(hours), size_hint=(.1, .15),pos_hint={'x':.9, 'y':.9})
        self.name_label = Label(text = "Game", size_hint=(.1, .15),pos_hint={'x':.45, 'y':.9})
        self.main_label = Label(text = "Default_text", size_hint=(1, .55),pos_hint={'x':0, 'y':.35})

    #Main Buttons
        self.inventory_button = Button(text = "Inventory", size_hint=(.3, .1),pos_hint={'x':.65, 'y':.2})
        self.help_button = Button(text = "Help", size_hint=(.3, .1),pos_hint={'x':.65, 'y':.1},on_press = self.update)
        self.craft_button = Button(text = "Craft", size_hint=(.3, .1),pos_hint={'x':.05, 'y':.1})
        self.food_button = Button(text = "Food", size_hint=(.3, .1),pos_hint={'x':.35, 'y':.2})
        self.go_button = Button(text = "Go", size_hint=(.3, .1),pos_hint={'x':.35, 'y':.1})
        self.walk_button = Button(text = "Walk", size_hint=(.3, .1),pos_hint={'x':.05, 'y':.2})

        self.add_widget(self.energy_label)
        self.add_widget(self.main_label)
        self.add_widget(self.time_label)
        self.add_widget(self.inventory_button)
        self.add_widget(self.help_button)
        self.add_widget(self.craft_button)
        self.add_widget(self.food_button)
        self.add_widget(self.go_button)
        self.add_widget(self.walk_button)
        self.add_widget(self.name_label)
        self.current_text = "Default"

    def update(self,event):
        self.main_label.text = "Changed to change"

class app1(App):
    def build(self):
        return Hello()
if __name__=="__main__":
     app1().run()