Search code examples
python-3.xcsvtkintercomboboxtkinter-canvas

combobox enter the empty field from csv file in Tkinter


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()

Issue:

  1. Combox is taking the empty cell also. In my application i need only the validate string as combobox list

  2. In the list the first entry is invisible

enter image description here


Solution

  • Look carefully on the for loop:

    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] 
    

    Therefore the first entry is missing in the selection list.

    Actually you can just remove the for loop, but keep only the last line in the for loop:

    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()]