Listing Option Menu Choices from Text File

Hello,

I am starting up a tool and one of the initial steps is to select a site/location which is being read from a text file.

Here is the text file contents:

site1
site2
site3

Here is the code:


#!/usr/bin/python

from Tkinter import *

root = Tk()
root.geometry("600x400")
root.title("Management E-mail")
# code here

# selecting sites title
title1 = Label (root, text = "What is the site Code?")
title1.pack(fill=X,padx=10)

# selecting sites sites

f = open("C:\Users\name\OneDrive\Python\sitelist.txt", "r")
list = f.read()

var=StringVar ()
var.set ('Click to Select Site')
sitelist = OptionMenu (root, var, *list)
sitelist.pack (fill=X,padx=10)

# input ticket number

title2 = Label (root, text = "What is the ticket number?")
title2.pack (fill=X,padx=10)

text1 = Entry ()
text1.pack(fill=X,padx=10)

listbox = Listbox ()
listbox.pack(side=LEFT,fill=BOTH, expand=1)						  
					  
root.mainloop ()

The problem is the output wherein OptionMenu is reading it per character:

Can you help me list it per site? Thank you in advanced!

Output should be:

site1
site2
site3

When you do list = f.read() , the entire content of file is read into list as a string. And as you know, python iterates over a string variable as if it is an array. And list here is an array of characters and hence your output is all characters one below the other. Here's how you intended to do it:

f = open("sitelist.txt", "r")
list = []
for line in f:
    list.append(line)
f.close()

And please always remember to close the filehandle after use.

1 Like
with open(r'C:\Users\name\OneDrive\Python\sitelist.txt') as f:
    sites = f.readlines()
var=StringVar ()
var.set ('Click to Select Site')
sitelist = OptionMenu (root, var, *sites)
sitelist.pack (fill=X,padx=10)

readlines() loads the file into an array, instead of read() which it loads the file as a string.
list is already used by Python as something else, I would avoid it.
"\n" can cause problems since it represents the end of line, use r'' for raw.
with open() takes care of the maintenance associated with opening a file.

1 Like

Thank you so much! This worked perfectly! Consider this as resolved. Thanks again!