我有一些 python 代码使用我的 SQL 表中的数据生成按钮。有没有办法我可以获取我选择的按钮的文本,因为我拥有的代码只会检索 for 循环中的最后一个值。我不能为每个按钮创建一个变量,因为每个站点都有不同数量的房间。
def search():
global screen13
global btn
global roomclicked
screen13 = Tk()
screen13.geometry("300x250")
screen13.title("Rooms")
sitename3_info = sitename.get().strip()
if sitename3_info:
cursor = cnn.cursor()
# combine the two SQL statements into one
sql = ("SELECT roomname FROM rooms, Sites "
"WHERE rooms.siteID_fk2 = Sites.siteID AND siteName = %s")
cursor.execute(sql, [sitename3_info])
rooms = cursor.fetchall()
# remove previous result (assume screen13 contains only result)
for w in screen13.winfo_children():
w.destroy()
if rooms:
for i, row in enumerate(rooms):
roomname = row[0]
roomclicked = roomname
btn = Button(screen13, text=roomname, command=lambda room=roomname: action(room))
btn.grid(row=i, column=0)
else:
Label(screen13, text="No room found").grid()
谢谢!