首页 > 解决方案 > Python Kivy Widgets

问题描述

I want to add two widgets or maybe three to form a page that show me Message and Take my input message and on pressing send button it pass that message to the send_msg() function Something like in Image:

Screenshot

I know the way to do it in py file but I need code for kv file Thank You in Advance for your help

Here is The Code:

class ChatPage(GridLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    # We are going to use 1 column and 2 rows
    self.cols = 1
    self.rows = 2

    # First row is going to be occupied by our scrollable label
    # We want it be take 90% of app height
    self.history = Label(height=Window.size[1]*0.9, size_hint_y=None)
    self.add_widget(self.history)

    # In the second row, we want to have input fields and Send button
    # Input field should take 80% of window width
    # We also want to bind button click to send_message method
    self.new_message = TextInput(width=Window.size[0]*0.8, size_hint_x=None, multiline=False)
    self.send = Button(text="Send")
    self.send.bind(on_press=self.send_message)

    # To be able to add 2 widgets into a layout with just one column, we use additional layout,
    # add widgets there, then add this layout to main layout as second row
    bottom_line = GridLayout(cols=2)
    bottom_line.add_widget(self.new_message)
    bottom_line.add_widget(self.send)
    self.add_widget(bottom_line)

   # Gets called when either Send button or Enter key is being pressed
   # (kivy passes button object here as well, but we don;t care about it)
    def send_message(self, _):
        print("send a message!!!")

标签: python-3.xkivykivymd

解决方案


很难让一个小部件占据GridLayout. 一个更简单的方法是 b 使用BoxLayouts

BoxLayout:
    orientation: 'vertical'
    ScrollView:
        size_hint_y: 0.9
        Label:
            id: label
            size_hint_y: None
            height: self.texture_size[1]
    BoxLayout:
        orientation: 'horizontal'
        size_hint_y: 0.1
        TextInput:
            id: ti
            size_hint_x: 0.8
        Button:
            text: 'send'
            size_hint_x: 0.2

推荐阅读