如何获取单击按钮的值

How can I get the value of a button clicked

我有一些 python 代码使用我 SQL table 中的数据生成按钮。有没有一种方法可以获得我选择的按钮的文本,因为我的代码只会检索 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()
        

谢谢!

编辑:您需要使用 class 来存储每个按钮的实例。

使用.cget()

from tkinter import *

screen13 = Tk()
screen13.geometry("300x250")
screen13.title("Rooms")

class buttongen():
    def __init__(self,x):
        self.btn = Button(screen13, text=word, command=lambda:print(self.btn.cget('text')))
        self.btn.pack()

for word in ('red', 'blue', 'orange', 'white'):
   buttongen(word)


screen13.mainloop()

我无法访问您的 table 但我尝试使用您的代码进行访问它应该可以工作

class buttongen():
    def __init__(self,i,row):
        self.i = i
        self.row = row

        self.roomname = self.row[0]
        roomclicked = self.roomname
        self.btn = Button(screen13, text=self.roomname, command=lambda :print(self.roomname))
        self.btn.grid(row=i, column=0)

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):
                buttongen(i, row)
                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()