Kivy传值问题:如何将新窗口TextBox的值传入指定函数
Got it, let's fix this step by step. The core idea is to link the button press event in each Row directly to the text value of that row's name input box, then pass that value to your RowsExtra.add_row() method instead of using a fixed string.
Step 1: Update your KV file (demo.kv)
First, make sure your Row component has an id assigned to the TextInput so we can reference its value. Then bind the button's on_press event to pass that value to add_row.
Here's how the Row rule might look:
<Row@BoxLayout>: # Assume your Row has an initial name value (like test1/test2) name: "" TextInput: id: name_input text: root.name # Bind to the Row's name property hint_text: "Enter name" Button: text: "+Add" # Pass the current row's TextInput value to add_row on_press: app.root.ids.rows_extra.add_row(root.ids.name_input.text)
Note: Replace app.root.ids.rows_extra with the actual path to your RowsExtra instance if your layout structure is different. For example, if RowsExtra is inside another container, adjust the id reference accordingly.
Step 2: Modify the RowsExtra class in demo.py
Update the add_row method to accept the textName parameter, which will now hold the dynamic value from the clicked row's input:
from kivy.uix.boxlayout import BoxLayout class RowsExtra(BoxLayout): def add_row(self, textName): # Now textName is the actual value from the clicked row's TextInput print(f"Received name: {textName}") # Your database query logic here using textName # Example: cursor.execute("SELECT * FROM table WHERE name = ?", (textName,))
Alternative: If you're creating Rows dynamically in Python
If you're building Row instances via Python code instead of KV, use functools.partial to pass the TextInput reference when binding the button press:
from kivy.uix.boxlayout import BoxLayout from kivy.uix.textinput import TextInput from kivy.uix.button import Button from functools import partial class Row(BoxLayout): def __init__(self, initial_name, **kwargs): super().__init__(**kwargs) # Create the name input box self.name_input = TextInput(text=initial_name) self.add_widget(self.name_input) # Create the button and bind the press event with the input value add_btn = Button(text="+Add") # Use partial to pass the TextInput as an argument to the callback add_btn.bind(on_press=partial(self.on_add_clicked, self.name_input)) self.add_widget(add_btn) def on_add_clicked(self, input_widget, button_instance): # Get the current text from the input box row_name = input_widget.text # Pass it to RowsExtra's add_row method app.root.ids.rows_extra.add_row(row_name)
This way, every time you click the "+Add" button in a row, it grabs the exact text from that row's input field and sends it to add_row for your database query.
内容的提问来源于stack exchange,提问作者Nirdesh Kumawat

