Reputation: 3
I'm currently trying to create a GUI for interacting with lines in a .txt file in order to sort the content of some freezer boxes. However it's difficult for me to interact with a specific line when i create a lot of buttons with a for-loop such as this:
def create_boxes(self):
for r in range(0,10):
for c in range(0,10):
self.button = Button(root, text='%s.%s'%(r,c),borderwidth=1 ,command= lambda: self.replace_line("Freezercontent.txt", r*10+c , input("What would you like in this slot"))).grid(row=r,column=c+5)
In the replace line function the second parameter is the linenumber the specific button needs to change. The solution i have does not work because when the lambda function is called upon with command the for-loop has finished. Meaning every button i click only changes the last line...
How can i access the buttons name given with the text="somename"
argument? Or is there an even smarter way of doing it?
Thanks and kind regards Emil H.
Upvotes: 0
Views: 115
Reputation: 56
The problem lies elsewhere.
I suggest not using lambda but instead creating a class which can be initialized during call to button with those coords of buttons.
The inner working would be in the class itself and it would know of its coords. You should create arrays of buttons also as suggested before me.
class Some:
def __init__(self, r, c):
self.r = r
self.c = c
def __call__(self):
# do what you need and access coords as self.c and self.r
Button(root, text='%s.%s' % (r,c), borderwidth=1, command=Some(r, c) ...
Upvotes: 1
Reputation: 24164
You could use a list comprehension to store all the buttons:
def create_boxes(self):
def make_replacer(r, c):
def replacer():
prompt = "What would you like in this slot"
self.replace_line("Freezercontent.txt",
r * 10 + c,
input(prompt))).grid(row=r,column=c+5)
return replacer
self.buttons = [Button(root,
text='%s.%s' % (r,c),
borderwidth=1,
command=make_replacer(r, c))
for r in range(0,10)
for c in range(0,10)]
Upvotes: 0
Reputation: 6777
The way you've currently coded it, it will let you access the last button created with self.button
. You could change this into a dictionary, and store them all there:
def create_boxes(self):
self.buttons = {}
for r in range(10):
for c in range(10):
text = '%s.%s' % (r, c)
self.buttons[text] = Button(root, text=text, borderwidth=1, command=...)
Then you can use self.buttons['1.1']
to get the button you need, etc.
Upvotes: 1