NameError: when instantiating a class in kv via a python statement in an event callback (e.g. on_parent)

huangapple go评论54阅读模式
英文:

NameError: when instantiating a class in kv via a python statement in an event callback (e.g. on_parent)

问题

我试图直接创建MyButton类的实例时,出现“NameError: name 'MyButton' is not defined”错误。为了解决这个问题,我在根部件中扩展了这个类(参见MuButton2),然后就没有问题了。有人能解释一下为什么会出现这种情况吗?

英文:

I get the error "NameError: name 'MyButton' is not defined" when I try to make an instance of MyButton class directly. As a workaround, I extend this class in root widget (see MuButton2) and then there is no problem. Can someone explain why this is the case?

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from itertools import cycle

Builder.load_string('''

<MyButton>:

<MainWidget>:
    
    BoxLayout:

        on_parent:
            for i in range(2,4): self.add_widget(root.MyButton2(text = str(i), pos=self.pos))    
            #for i in range(1,3): self.add_widget(MyButton(text = str(i), pos=self.pos)) #<-- results in NameError: name 'MyButton' is not defined   

        MyButton: #<-- however this works fine
            text: '1'
''')

class MyButton(Button):

    def __init__(self, **kwargs):
        super(Button, self).__init__(**kwargs)    
        self.colours=cycle([(1,0,0,1),(0,1,0,1),(0,0,1,1)])
        
    def on_press(self):
        self.background_color=next(self.colours)

        
class MainWidget(BoxLayout):

    class MyButton2(MyButton):
        pass

class MyApp(App):
    def build(self):
        return MainWidget()
      
if __name__ == '__main__':
    MyApp().run()

答案1

得分: 1

你可以通过使用 kivy.factory.Factory 来解决这个问题。在你的 kv 字符串的开头添加:

#:import Factory kivy.factory.Factory

然后,使用它:

for i in range(1,3): self.add_widget(Factory.MyButton(text=str(i), pos=self.pos))
英文:

You can fix that problem by using kivy.factory.Factory. Add to the beginning of your kv string:

#:import Factory kivy.factory.Factory

And then, use it as:

for i in range(1,3): self.add_widget(Factory.MyButton(text = str(i), pos=self.pos))

huangapple
  • 本文由 发表于 2023年5月15日 06:41:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76249973.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定