簡體   English   中英

刪除kivy小部件中的按鈕

[英]Remove a button in the kivy widget

在kivy中,我嘗試刪除窗口小部件中的按鈕,但這不起作用,我猜這是因為我的定位不正確,但是我在互聯網上找不到這樣做的好方法。

我想在單擊另一個按鈕時刪除一個按鈕

class RPS(Widget):
    user_name_input = ObjectProperty()
    user_name = ''

    def save_user_name(self):
        user_name = self.user_name_input.text
        print(user_name)
        self.remove_widget(self.ids.remove) # I guess the problem is here the way I target

獼猴桃文件

user_name_input: user_name
TextInput:
    id: user_name
    size: 300, 50
    pos: 700,400
Button:
    text: "name"
    pos: 1070,400
    size: 300, 50
    on_release: root.save_user_name()
Button:
    id: remove
    text: "button to remove"
    pos: 1070,800
    size: 300, 50

解決方法如下。 在示例中,我使用了一個ObjectProperty來掛接要刪除的按鈕,因為id是對小部件的弱引用。 作為“最佳實踐”,請使用ObjectProperty,因為這將創建直接引用,提供更快的訪問權限並且更加明確。 有關詳細信息,請參閱示例。

main.py

from kivy.properties import ObjectProperty, StringProperty


class RPS(BoxLayout):
    btn = ObjectProperty(None)
...
    self.remove_widget(self.btn) # I guess the problem is here the way I target

KV文件

#:kivy 1.10.0

<RPS>:
    btn: remove

main.py

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty, StringProperty


class RPS(BoxLayout):
    btn = ObjectProperty(None)
    user_name_input = ObjectProperty(None)
    user_name = StringProperty('')

    def save_user_name(self):
        self.user_name = self.user_name_input.text
        print(self.user_name)
        self.remove_widget(self.btn)


class TestApp(App):
    def build(self):
        return RPS()


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

測試文件

#:kivy 1.10.0

<RPS>:
    btn: remove
    user_name_input: user_name
    TextInput:
        id: user_name
        size: 300, 50
    Button:
        text: "name"
        size: 300, 50
        on_release: root.save_user_name()
    Button:
        id: remove
        text: "button to remove"
        size: 300, 50

輸出量

圖1-移除前按鈕 圖2-卸下的按鈕

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM