0

So, basically I'm trying to make a control menu in my tkinter app, and make a button open a file and save it to a variable. I want to see if I can do that using only lambda functions instead of normal functions (as in defining functions). Is there any way I can do that with the given code? (Thanks very much.)

from tkinter.filedialog import askopenfilename
import tkextra as tke
import os

root = tk.Tk()
controlMenuBox = tk.Menu(root)

openFile = lambda initialDirectory, title, fileTypes : \
    askopenfilename(initialdir=initialDirectory, title=title, filetypes=fileTypes)

fileMen = tk.Menu(controlMenuBox, tearoff=0)
controlMenuBox.add_cascade(label='File', menu=fileMen)
fileMen.add_command(label='Open File',
                    command=lambda: openFile("/", "Open File", (("Text files", "*.txt"), ("all files", "*.*"))))

homeMenu = tk.Canvas(root, width=800, height=600, bg="#fff7e8")
homeMenu.pack()

root.config(menu = controlMenuBox)
root.mainloop()
Tech Zachary ZN
  • 109
  • 1
  • 3
  • There's no point in using a `lambda` if you're naming the function. Use `def openFile` – Barmar Oct 17 '22 at 21:54
  • 1
    You can't assign global variables in lambda functions. You can assign variables using the walrus operator, but they're local to the function. There's no way to put a `global` statement in a lambda. – Barmar Oct 17 '22 at 21:58
  • 1
    Why don't you want to use a function? Functions are much easier to understand, write, and debug. – Bryan Oakley Oct 17 '22 at 22:23
  • I just wanted to know if there was any way to use a lambda in this scenario. Thanks for the info, and I will go to changing my code. – Tech Zachary ZN Oct 17 '22 at 23:17

1 Answers1

0

There is unfortunately no way to use a lambda function in this scenario, and the easiest way to do this would to be to use a function.

def openFile(initialDirectory, title, fileTypes):
    ...
Tech Zachary ZN
  • 109
  • 1
  • 3