我對 python 和 RPi 很陌生。我正在嘗試基于 MySQL 查詢生成動態按鈕。我在論壇中找到了這個帖子:如何在 tkinter 中創建一個自調整大小的按鈕網格?
了解如何在網格中生成動態按鈕很有幫助。不過,我在為每個動態按鈕和圖片設定命令時遇到問題。
這是我的代碼:
from __future__ import division
import tkinter as tk
from tkinter import *
import MySQLdb
db = MySQLdb.connect("localhost", "User...", "SecurePW", "myCoolDB")
curs=db.cursor()
PhotoImageFolder='/home/pi/App/CocktailPic/'
root = Tk()
Grid.rowconfigure(root, 0, weight=1)
Grid.columnconfigure(root, 0, weight=1)
#Create & Configure frame
frame=Frame(root)
frame.grid(row=0, column=0, sticky=N S E W)
curs.execute("SELECT * FROM `CockRec` WHERE `IsACTIVE`=1")
max_col_index=10
col_index=0
row_index=0
def CocktailBtnCmd(Cocktail_ID):
messagebox.showinfo(title='Informatio', message=Cocktail_ID)
#print("Cocktail ID: ",Cocktail_ID)
for entry in curs.fetchall():
if col_index>=max_col_index:
row_index=row_index 1
col_index=0
CocktailID=entry[0]
Cocktail=entry[1]
CocktailPicturePath=entry[3]
btn_image=PhotoImage(file = PhotoImageFolder CocktailPicturePath)
photoImage = btn_image.subsample(10, 10)
Grid.rowconfigure(frame, row_index, weight=1)
Grid.columnconfigure(frame, col_index, weight=1)
btn = Button(frame, text = Cocktail, image=photoImage, command = CocktailBtnCmd(CocktailID)) #create a button
btn.grid(row=row_index, column=col_index, sticky=N S E W)
col_index=col_index 1
問題是,當我運行代碼時,它只在最后一個按鈕上顯示圖片,而且按鈕后面的命令也不起作用。
如果我在 For LOOP 之前定義圖片,它至少適用于每個按鈕上的所有相同圖片。
任何想法,我做錯了什么?
uj5u.com熱心網友回復:
command=CocktailBtnCmd(CocktailID)將CocktailBtnCmd(...)立即執行并將結果(即None)分配給command選項。這就是按鈕稍后不起作用的原因。
您需要使用lambda帶默認值的 using 引數:
command=lambda CocktailID=CocktailID: CocktailBtnCmd(CocktailID)
對于影像問題,這是因為您在 for 回圈中使用了相同的變數來保存影像的參考:
photoImage = btn_image.subsample(2, 2)
所以在 for 回圈之后,只有最后一個影像參考了它,之前的影像將被垃圾收集。
您可以使用相關按鈕的屬性保留所有影像的參考:
for entry in curs.fetchall():
...
photoImage = btn_image.subsample(2, 2)
...
btn = Button(frame, text = Cocktail, image=photoImage, command=lambda: CocktailID=CocktailID: CocktailBtnCmd(CocktailID))
btn.image = photoImage # use an attribute to keep the reference of image
...
另外我建議使用官方mysql.connector模塊而不是MySQLdb.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/425929.html
下一篇:Python調度程式中的例外
