![](/img/trans.png)
[英]How do I add buttons that are dynamically created in pure python to a kivy layout that is Written in Kivy Language?
[英]Python (Kivy) - How to dynamically add buttons and bind with different arguments
我已經了解了如何在 kivy 中動態添加按鈕,以及如何將它們綁定到具有額外 arguments 的方法。
我將嘗試使用 Car 示例盡可能好地描述我的問題:我有點使用 MVC。 用戶應該能夠看到汽車列表,他還能夠編輯、添加和刪除(基本的 CRUD)。 汽車 Model 具有 id、car_name 和 description 等屬性
controller 執行 CRUD 操作。 寫入時會將數據存儲在 .json 文件中,讀取時會將所有數據存儲在變量中。 我對 Controller 或 Model 沒有任何問題,這工作正常。
現在我想顯示用戶在我的視圖 (Kivy) 中創建的所有汽車。 我決定所有汽車都將在主窗口中顯示為帶有汽車名稱的按鈕。 當我點擊按鈕時,它應該會顯示一個包含汽車信息的新屏幕。 但我不知道如何從單擊的按鈕傳遞汽車的 id ......所以這就是我的代碼到目前為止(不工作):
class MainWindow(GridLayout):
def __init__(self, **kwargs):
super(MainWindow, self).__init__(**kwargs)
self.cols = 1
for car in car_cache.car_list:
btn_car = Button(text=car.car_name, font_size=40)
btn_car.bind(on_press=lambda x: self.select_car(btn_car, car.id))
self.add_widget(btn_car)
def select_car(self, instance, id):
print(f'Car {id} selected')
按鈕顯示正確。 問題是,無論我點擊什么按鈕,它總是打印添加到小部件的汽車的最后一個 ID。
感謝您的幫助。
我的問題下的兩條評論解決了我的問題。 對於第一條評論:
class MainWindow(GridLayout):
def __init__(self, **kwargs):
super(MainWindow, self).__init__(**kwargs)
self.cols = 1
for car in car_cache.car_list:
self.btn_car = Button(text=car.car_name, font_size=40)
self.btn_car.bind(on_press=partial(self.select_car, car.id))
self.add_widget(btn_car)
def select_car(self, id, instance):
print(f'Car {id} selected')
partial 需要從 functools 導入。 注意 function 'select_car' 中的參數 id 和 instance 發生了變化。
對於第二條評論:
class MainWindow(GridLayout):
def __init__(self, **kwargs):
super(MainWindow, self).__init__(**kwargs)
self.cols = 1
for car in car_cache.car_list:
self.btn_car = Button(text=car.car_name, font_size=40)
self.btn_car.bind(on_press=lambda x, bound_car=car:
self.select_car(self.btn_car, bound_car.id))
self.add_widget(btn_car)
def select_car(self, instance, id):
print(f'Car {id} selected')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.