micma
micma

Reputation: 223

Drop Down Menu In Python calling information from files

So I need a drop down menu, where the user picks his/her client, and it returns information about that client.

lets say i have a file:

["client1", "client2", "client3"]

and I have this code:

from tkinter import *

master = Tk()

with open('ubclientlistvars.txt', 'r') as clients:
    clients = (clients.readlines())


variable = StringVar(master)
variable.set("Choose Client")

w = OptionMenu(master, variable, clients)
w.pack()

mainloop()

how would I draw the clients from the file into the drop down menu? When I run this code, i get these two options: Choose Client and {["client1", "client2", "client3"]}

Upvotes: 0

Views: 1431

Answers (1)

ChrisP
ChrisP

Reputation: 5942

You need to actually parse that file. If the file contents are what you posted, then readlines() is just returning a single line of text. It does not magically convert the file contents into a Python object. Suppose the file was:

client1
client2
client3

Then you could use something like clients = [i.strip() for i in f.readlines()] to get a proper list of clients and can pass them to OptionMenu:

w = OptionMenu(master, variable, *clients)

If you cannot change the file format then you will need to clean up the input before displaying it...

import re
data = f.read()  # ["client1", "client2", "client3"]
data = re.sub('["\[\]]', '', data)  # remove the ", [, and ] characters
clients = data.split(',')  # split the list of clients on the comma

Upvotes: 3

Related Questions