如何在实例类(后端)和Kivy图形元素(前端)之间共享数据?

2024-09-28 17:21:43 发布

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

我是Kivy的初学者,我正在尝试为python应用程序创建gui。 我有一个用python编程的后端,单独工作(键盘作为输入),现在我希望前端使用kivy。我有两个问题: -如何同时运行两个组件(后端和前端)? -如何在后端共享现有类的对象以在前端(kivy)显示信息?你知道吗

你知道吗类测试.py你知道吗

class Test(object):
  def __init__(self, attr):
    self.attr = attr

你知道吗图形用户界面.py你知道吗

class LoginScreen(GridLayout):
  def __init__(self, **kwargs):
    super(LoginScreen, self).__init__(**kwargs)
    self.cols = 2
    self.add_widget(Label(text='User Name'))
    self.username = TextInput(multiline=False)
    self.add_widget(self.username)
    self.add_widget(Label(text='password'))
    self.password = TextInput(password=True, multiline=False)
    self.add_widget(self.password)
    print self.username.text

class Login(App):

  def build(self):
    Window.borderless = True
    return LoginScreen()    

你知道吗主.py你知道吗

import classtest, gui
users = ['user_name1', 'user_name2', 'user_name3']    
gui.Login().run()
for u in users:
  test = classtest.Test(u) # this should update the user text field on the windows login automatically, but how?

在示例中,当实例属性值更改时,如何更新登录窗口的元素?你知道吗

多谢了!你知道吗


Tags: textpyselfaddinitdefusernamegui
1条回答
网友
1楼 · 发布于 2024-09-28 17:21:43

它不会更新,因为。。。循环:P Kivy for eachApp().run()或类似的“run”命令启动一个循环,您的:

for u in users:
    test = classtest.Test(u)

写在循环之后。所以基本上它甚至不会在你的应用程序运行时执行。只要把print('something')放到for循环中,您就会看到。你知道吗

示例:

while True:
    <do something>
<change a variable in that loop>  # == nope

这意味着你需要:

  • 将其写入gui.py文件
  • 把那些东西放在正确的地方类测试.py你知道吗

第二个选项还取决于使用类的时间。如果在主循环之外,那么您的情况与现在相同,因此-在gui.py内部使用Test()。你知道吗

当应用程序运行时,run()之后您将无法使用任何代码。也许是一些肮脏的把戏,但那只会给你带来麻烦。您编写的代码可以用于某些“清理”,也可以在App.on_stop方法(在主循环内)中进行清理。你知道吗

相关问题 更多 >