用Tkinter Python创建多个带有子窗口的按钮

2024-04-20 12:00:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Accountid列。现在我用Tkinter绘制一些图形用户界面。我想为每个Accountid创建一个单独的按钮。我的代码可以做到这一点。但是在这之后,我想为每个按钮创建一个子窗口,其中包含每个Accountid的一些列。现在的问题是,我的代码为每个按钮创建子窗口,但它只获取最后一个Accountid的列。在

如果有人能帮我,我会非常感激的。在

import tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):

        tk.Frame.__init__(self, parent)
        for id in df['AccountId']:##for each id create a button

            new_win_button = tk.Button(self, text=id, 
                                   command= self.new_window)
            new_win_button.pack(side="top", padx=20, pady=20)


    def new_window(self):

        top = tk.Toplevel(self)# create sub window
        print (id)
        #print (id is 'id')
        label = tk.Label(top, text=s3.loc[s3.AccountId == id][['AccountId','confidence','lift']])

        label.pack(side="top", fill="both", expand=True, padx=20, pady=20)


if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()​

Tags: 代码selfidnewexampletopbuttonroot
1条回答
网友
1楼 · 发布于 2024-04-20 12:00:57

在这个循环之后:

for id in df['AccountId']:##for each id create a button

            new_win_button = tk.Button(self, text=id, 
                                   command= self.new_window)
            new_win_button.pack(side="top", padx=20, pady=20)

id是类Example的局部变量。并且id被设置为上述for循环末尾df['AccountId']的最后一个值。例如:

^{pr2}$

结果:

9

所以

label = tk.Label(top, text=s3.loc[s3.AccountId == id][['AccountId','confidence','lift']])

比较s3.AccountId == id将始终与最新值id匹配,这就是为什么总是只获取最后一个Accountid的列。在

解决方法

import tkinter as tk
import pandas as pd

root = tk.Tk() #declare root in global scope for simplicity


class new_button:

    def __init__(self,A_id):

        self.id=A_id
        but = tk.Button(root,text=self.id,command=self.new_window)
        but.pack(side="top", padx=20, pady=20)



    def new_window(self):

        top = tk.Toplevel(root)# create sub window

        label = tk.Label(top, text=s3.loc[s3.AccountId == self.id][['AccountId','confidence','lift']])

        label.pack(side="top", fill="both", expand=True, padx=20, pady=20)


if __name__ == "__main__":
    for i in df['AccountId']:##for each id create a button

            butt=new_button(A_id=i)

    root.mainloop()

创建了一个new_button类,该类为dataframe中的每个AccountId创建一个唯一的按钮。在

相关问题 更多 >