0

我有一些 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()
        

谢谢!

4

1 回答 1

0

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

利用.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()

我无权访问您的表格,但我尝试使用您的代码进行操作,它应该可以工作

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()
于 2021-01-21T10:58:40.653 回答