Let's say I have a text file which contains 10 numbers
I have written a code to select and open the file, the default window shows a pushbutton to select it and an empty combobox
I would like to fill the combobox with values from the file when it is opened but without close the window
from tkinter.filedialog import askopenfilename
import os
import tkinter as tk
from tkinter import ttk
class Application(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
ButtonSelect_File = tk.Button(self, text='Select file', command=self.displayPath)
ButtonSelect_File.grid(row=1, column=0)
self._File = tk.StringVar(self)
self._File.set('')
label_File = tk.Label(self, textvariable=self._File)
label_File.grid(row=1, column=1)
self.combobox = ttk.Combobox(self, values=[])
self.combobox.grid(row=2, column=0)
def displayPath(self):
self.File = askopenfilename()
self.directory = os.path.split(self.File)[0]
self._File.set(self.File)
def readFile(self, file):
read = open(file, "r")
values = [i for i in read]
### HOW TO ADD THESE VALUES TO THE COMBOBOX ####
if __name__ == "__main__":
obj = Application()
obj.mainloop()
obj.readFile(obj.File)
Could someone tell me how to do that ?
CodePudding user response:
I refactored your code to make a clear connection between your Button, file loading, and injecting values into your Combobox. I don't personally feel like there is anything here that needs explanation, but here goes. When you click your button the command
is called which runs the load_values
method. In that method askopenfilename
is invoked and that will allow you to load a file. Once the file is loaded we use list comprehension to form a list that consists of all the lines in the file. That list is then assigned to the Combobox
via it's values
key. Finally we store the first value in the Combobox
via the StringVar
that was assigned to it's textvariable
key. We end by assuring that this is the __main__
script, and if so, we initiate our app and invoke it's mainloop
.
In short, it's everything that you were already doing with 4 lines added that convert the file to values, and a bunch of unrelated things removed.
from tkinter.filedialog import askopenfilename
import tkinter as tk, tkinter.ttk as ttk
import os
class Application(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
loadbtn = tk.Button(self, text='Select file', command=self.load_values)
loadbtn.grid(row=1, column=0)
self._pv = tk.StringVar(self)
pathlbl = tk.Label(self, textvariable=self._pv)
pathlbl.grid(row=1, column=1)
self._cbv = tk.StringVar()
self._cb = ttk.Combobox(self, textvariable=self._cbv)
self._cb.grid(row=2, column=0)
def load_values(self):
path = askopenfilename()
self._pv.set(path)
with open(path, "r") as f:
v = [l.strip() for l in f.readlines()]
self._cb['values'] = v
self._cbv.set(v[0])
if __name__ == "__main__":
Application().mainloop()