【问题标题】:combobox enter the empty field from csv file in Tkinter组合框从 Tkinter 中的 csv 文件中输入空字段
【发布时间】:2021-11-01 14:50:20
【问题描述】:
enter code here 
import tkinter as tk
import tkinter.ttk as ttk
import csv

class Application(tk.Frame):
def __init__(self, root):
    self.root = root
    self.initialize_user_interface()

def initialize_user_interface(self):
     self.button2 = tk.Button(self.root, text="Summary", command=self.summary_data)
    self.button2.grid(row=0, column=1)


def summary_data(self):
  n = tk.StringVar(value="choose location")
  summarychoosen = ttk.Combobox(self.root, width = 20, textvariable = n);
  summarychoosen.grid(row=1, column=1, sticky="wesn")
  with open('UI_LLD.csv') as f:
    reader = csv.DictReader(f, delimiter=',')
    for row in reader:
        aSummary = row['Summary']
        print(aSummary)
        summarychoosen['values'] = [row['Summary']for row in reader] 

app = Application(tk.Tk())
app.root.mainloop()

问题:

  1. Combox 也使用空单元格。在我的应用程序中,我只需要验证字符串作为组合框列表

  2. 在列表中第一个条目是不可见的

enter image description here

【问题讨论】:

  • 使用 strip 删除空字符串,或者只做类似 if i == "": continue
  • 你能解释一下为什么它不获取第一个元素数据

标签: python-3.x csv tkinter combobox tkinter-canvas


【解决方案1】:

仔细查看for循环:

for row in reader:
    aSummary = row['Summary'] # read the first line
    print(aSummary)
    # read the remaining lines
    summarychoosen['values'] = [row['Summary']for row in reader] 

因此选择列表中缺少第一个条目。

其实你可以去掉for循环,只保留for循环的最后一行:

with open('UI_LLD.csv') as f:
    reader = csv.DictReader(f, delimiter=',')
    # added "if" to filter out empty lines
    summarychoosen['values'] = [row['Summary'] for row in reader if row['Summary'].strip()]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-11
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-24
    • 1970-01-01
    相关资源
    最近更新 更多