Python:点击按钮后在可滚动BoxLayout中添加MySQL数据按钮无响应
It’s frustrating when a function runs without errors but does nothing—let’s walk through the most likely causes and fixes for your scenario:
1. Verify Your Query Returns Data
First, confirm that your SQL query is actually fetching rows. Add a print statement right after fetchall() to check if there’s any data:
result = cursor.fetchall() print("Fetched results:", result) # Add this line to debug
- If the output is an empty list (
[]), your query isn’t matching any records. Double-check:- Is the table name
costumerinfospelled correctly (typos like missing an 'm' incustomerare common)? - Does the
Cos_namecolumn exist in your table with that exact casing? - Case sensitivity: MySQL’s collation might be case-sensitive. Try
'a%'instead of'A%', or useLOWER(Cos_name) LIKE 'a%'to match regardless of case.
- Is the table name
2. Ensure You’re Creating & Adding Buttons
Your code snippet cuts off after fetching results—are you looping through the data to create buttons and add them to your nodes BoxLayout? Here’s how that critical part should look:
for row in result: cos_name = row[0] # Create a button for each customer name btn = Button(text=cos_name, size_hint_y=None, height=40) # Optional: Add an on-press handler if needed # btn.bind(on_press=lambda x, name=cos_name: self.handle_button_press(name)) self.nodes.add_widget(btn)
If you’re missing this loop, no buttons will be added—even if the query returns valid data.
3. Check if nodes ObjectProperty is Properly Bound
Make sure your nodes ObjectProperty is correctly linked to your scrollable BoxLayout in your KV file. For example:
<YourWidgetClass>: ScrollView: BoxLayout: id: scrollable_box orientation: 'vertical' size_hint_y: None height: self.minimum_height
Then in your Python code, bind the ObjectProperty to the KV id:
class YourWidgetClass(Widget): nodes = ObjectProperty(None) def __init__(self, **kwargs): super().__init__(**kwargs) self.nodes = self.ids.scrollable_box # Link the id to the property
If nodes is None, calling self.nodes.add_widget() will silently fail (no error, but no action).
4. Avoid Blocking the Main Thread
Database operations can block the UI thread, making it seem like nothing is happening. Wrap your DB call in a thread and use Kivy’s Clock to update the UI safely:
from kivy.clock import Clock import threading def a_but(self): def fetch_and_update(): # Perform DB operations in a background thread db = mysql.connector.connect(user='****', password='*******', host='localhost', db='***') cursor = db.cursor() cursor.execute("SELECT Cos_name FROM costumerinfo WHERE Cos_name LIKE 'A%'") result = cursor.fetchall() cursor.close() db.close() # Schedule UI updates on the main thread Clock.schedule_once(lambda dt: self.add_buttons_to_layout(result)) threading.Thread(target=fetch_and_update).start() def add_buttons_to_layout(self, result): # This runs on the main thread to update the UI for row in result: btn = Button(text=row[0], size_hint_y=None, height=40) self.nodes.add_widget(btn)
This prevents UI freezes and ensures widgets are added correctly.
5. Catch Silent Exceptions
Even without visible errors, exceptions might be getting swallowed. Wrap your DB code in a try-except block to reveal hidden issues:
def a_but(self): try: db = mysql.connector.connect(user='****', password='*******', host='localhost', db='***') cursor = db.cursor() cursor.execute("SELECT Cos_name FROM costumerinfo WHERE Cos_name LIKE 'A%'") result = cursor.fetchall() # ... button creation logic ... cursor.close() db.close() except Exception as e: print("Hidden error:", str(e))
This will uncover issues like incorrect credentials, missing database, or connection timeouts.
Start with these checks—most likely the problem is either no data being returned, missing button creation logic, or an unbound nodes property.
内容的提问来源于stack exchange,提问作者I want to know

