0

So here is my code:

from tkinter import *
import os

def playWAD(filename):
    wadlistthing =(GZwadPath, filename)
    playwad = '\\'.join(wadlistthing)
    os.startfile(playwad)
paths = open('config.txt', 'r')
root = Tk()
root.title("GZlauncher")
root.configure(background="black")

GZwadPath = paths.readline(30)
paths.close
wads = os.listdir(GZwadPath)
rownum=2
for file in wads:
    Button(root, text="PLAY", width=4, command=lambda: playWAD(file)) .grid(row=rownum, column=1, sticky=N)
    Label(root, text=file, bg="black", fg="white") .grid(row=rownum, column=2, sticky=N)
    rownum +=1

root.mainloop()

The problem is that I get a list of wads like I should, but when I press the play button it opens the last one loaded.

How do I fix this?

Learner
  • 29
  • 1
  • 5
k7x1e
  • 1

1 Answers1

0

It is the problem with lambda function, as each time the forloop goes the value of variable file changes. at the end value of file is the last item in list wads. So you will have to use this trick way:

from tkinter import *
import os
from functools import partial

def playWAD(filename):
    wadlistthing =(GZwadPath, filename)
    playwad = '\\'.join(wadlistthing)
    os.startfile(playwad)
paths = open('config.txt', 'r')
root = Tk()
root.title("GZlauncher")
root.configure(background="black")

GZwadPath = paths.readline(30)
paths.close
wads = os.listdir(GZwadPath)
rownum=2
for file in wads:
    Button(root, text="PLAY", width=4, command=partial(playWAD, file)).grid(row=rownum, column=1, sticky=N)
    Label(root, text=file, bg="black", fg="white") .grid(row=rownum, column=2, sticky=N)
    rownum +=1

root.mainloop()
AmaanK
  • 1,032
  • 5
  • 25