I hope you can help me, because I am stuck on this. I have an application on tkinter, bassically I need that when pressing a button a function from another python file is executed and changes the text of a label.
Let me explain:
My frontend file is called ODF_principal.py and my backend file is called ODF_second.py, in the backend file I have functions.
I imported ODF_second.py asOFU on ODF_principal to set command in button properties like the following:
btn_Open = Button(frame_menu, text="Open file", command=OFU.open_file)
btn_Open belongs to frontend
Well, when I run the function, I need that when a file is opened or not, change the text of a label that belongs to the frontend file.
lbl_file = Label(frame_menu)
I've tried to import the frontend file into de backend but I've got an error of CIRCULAR IMPORT, so here is the function that I need it to be able to change the text of lbl_file
opened_file_path=""
def open_file():
global opened_file_path
opened_file_path=filedialog.askopenfilename(initialdir = "/",
title = "Select files",filetypes = (("TXT files","*.txt"),
("All files","*.*")))
if not opened_file_path:
opened_file_path = ""
**OFR.lbl_file.config(text=opened_file_path)**
Thank you for your time.
CodePudding user response:
You can achieve this using a lambda function:
btn_Open = Button(frame_menu, text="Open file", command= lambda: OFU.open_file(lbl_file))
And then
def open_file(label):
global opened_file_path
opened_file_path=filedialog.askopenfilename(initialdir = "/",
title = "Select files",filetypes = (("TXT files","*.txt"),
("All files","*.*")))
if not opened_file_path:
opened_file_path = ""
label.config(text=opened_file_path)
The lambda function allows you to pass a reference to the label to your function in the other file.
CodePudding user response:
You can achieve this by getting open_file to return the file path and altering the label in your frontend.
def button_press():
file_open = OFU.open_file
my_label.configure(text=file_open)
btn_Open = Button(frame_menu, text="Open file", command=button_press)
And
def open_file():
opened_file_path=filedialog.askopenfilename(initialdir = "/",
title = "Select files",filetypes = (("TXT files","*.txt"),
("All files","*.*")))
if not opened_file_path:
opened_file_path = ""
return opened_file_path
This is an alternative to @Henry's answer that means your backend doesn't have to handle any of the GUI
