在运行时更改 Kivy 中 Popup 项目的位置

change the position of an item from a Popup in Kivy during runtime

我的objective是想从Popup输入一个十进制数到TextInput。然后输入将用于在运行时更改主屏幕上按钮的 size_hint_x。 这是我的尝试:

Python 文件


from kivy.app import App
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.popup import Popup
Builder.load_file('question.kv')


class Pop_up(Popup):
    def open_window(self):
        self.open()
    def close_window(self):
        self.dismiss()
        number_typed = self.ids.text_box_in_popup.text
        a = main()
        a.change_position(number_typed)


class main(FloatLayout):
    def change_position(self, number_typed):
        movable_button = self.ids.movable_button
        movable_button.size_hint_x = number_typed
        # ~ this is the attempt of me trying to change the size_hint_x of the button
        # it doesn't produce an error but doesn't work either


class testApp(App):
    def build(self):
        return main()


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

.kv 文件

#:import Factory kivy.factory.Factory
<Pop_up>
    title: "type in a decimal number, I want to change the size_hint_x of the button to that number"
    size_hint: 0.5, 0.5
    pos_hint:{'center_x':0.25, "center_y":0.25}
    BoxLayout:
        orientation: "vertical"
        TextInput:
            id: text_box_in_popup
            size_hint: 1, 2


        Button:
            text: "update_position"
            on_release: root.close_window()
<main>
    Button:
        id: movable_button
        text: "movable_button"
        size_hint: 0.25, 0.25
        pos_hint: {'center_x':0.5, "center_y":0.5}
        on_release: Factory.Pop_up().open_window()

我尝试使用 self.ids.movable_button.size_hint_x = number_typed,但它没有用,尽管它没有产生任何错误。

在您的 close_window() 方法中,行:

a = main()

正在创建 main class 的新实例。但是,这个新实例不是您的 GUI 的一部分,您对其所做的任何更改都不会影响您在显示屏上看到的内容。为了执行您想要的操作,您必须访问显示中的 main 实例。您可以通过将上面的行替换为:

来获取对该实例的引用
a = App.get_running_app().root