使用textvariable

时间:2019-03-12 11:58:38

标签: python-3.x tkinter

我正在使用tkinter并使用textvariable创建一个标签。我要说的是在这个标签中列出前5名客户。客户列表来自excel文件。

部分代码:

import pandas as pd
import tkinter as tk
from tkinter import ttk

df = pd.read_excel('Sample.xlsx', "Sheet1")

class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.grid_rowconfigure(1, weight=1)
        self.grid_columnconfigure(1, weight=1)
        self.grid()

        self.baseDown = tk.Frame(root, width=800, height = 400, background='#E6E6FA', relief = "groove", borderwidth = 2)
        self.baseDown.grid(columnspan=7, row=1, rowspan = 4, pady = 1, padx = 2, sticky="wn")
        self.BDown = tk.LabelFrame(self.baseDown, text = " Analysis ", width=800, height=400, background ='#E6E6FA', relief = 'ridge', borderwidth = 2)
        self.BDown.config(font = ('Verdana', 8, 'bold'))
        self.BDown.grid(columnspan=7, row=1, rowspan = 4, pady = 3, padx = 2, sticky="wn")
        self.baseDown.grid()

        self.cust_var = tk.StringVar()
        self.lbl_custname = ttk.Label(self.BDown, textvariable = self.cust_var)
        self.lbl_custname.config(font=('Segoe UI', 8), width = 100)
        self.lbl_custname.grid(row=1, column=1, columnspan=3, pady = 1, padx = 2, sticky="nw")

        top = df.nlargest(5, columns=['Value'])
        for index, row in top.iterrows():
            self.cust_var.set(row[top['Customer Name'].values.astype(str)])


root = tk.Tk()
root.configure(background = 'white')
#root.resizable(False, False)
app = Application(master=root)
app.mainloop()

输出如下: 客户1 NaN 客户2 NaN 客户3 NaN 客户4 NaN 客户5 NaN 名称:20371,dType:对象

客户列表是正确的,但是我不明白为什么存在NaN以及为什么还会显示数据类型。

我的excel文件仅包含2列: 顾客姓名 值

1 个答案:

答案 0 :(得分:0)

您将self.cust_var设置为row[top['CustomerName'].values.astype(str)]的结果5次。

如果要显示期望的结果,只需将变量设置一次(替换for循环):

self.cust_var.set('\n'.join(top['Customer Name'].values))