0

i'm not very good in Python especially when using classes. I write this code to set the Entry value using a browse button, the problem is that in this way i should create a browse method for each button. There is a easier way to solve this problem?

from tkinter import *
from tkinter.filedialog import askopenfilename

class App:
    def __init__(self, parent):        
        self.button1 = Button(text = 'browse', command = self.browse1)     
        self.button1.grid (row = 0, column = 1)

        self.input_file1 = Entry(textvariable = self.browse1)
        self.input_file1.grid(row=0, column = 0)

        self.button2 = Button(text = 'browse', command = self.browse2)     
        self.button2.grid (row = 1, column = 1)

        self.input_file2 = Entry(textvariable = self.browse2)
        self.input_file2.grid(row=1, column = 0)

    def browse1(self):
        filename = askopenfilename(title = 'Select a file')
        self.input_file1.delete(0, END)
        self.input_file1.insert(0, filename)

    def browse2(self):
        filename = askopenfilename(title = 'Select a file')
        self.input_file2.delete(0, END)
        self.input_file2.insert(0, filename)

root = Tk()
root.geometry('900x550')
root.title('prove') 
MyApp = App(root)  
root.mainloop()

Thank you!

1

1 Answer 1

1

If you have your function as this:

def browse(self, entry):
    filename = askopenfilename(title = 'Select a file')
    entry.delete(0, END)
    entry.insert(0, filename)

and then change your definitions to this:

self.button1 = Button(text = 'browse', command = lambda: self.browse(self.input_file1))     
self.button1.grid (row = 0, column = 1)

self.input_file1 = Entry()
self.input_file1.grid(row=0, column = 0)

Then when the button is pressed, it calls the lambda function which calls the browse() function, passing the corresponding entry field to the function which can then insert the text.

Hope this makes sense, let me know if you have any problems :)

Sign up to request clarification or add additional context in comments.

1 Comment

Great!! thank you now it works i was sure that it wouldn't be difficult!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.