Reputation: 53
I have code like this (just part of a code). I need when someone click on the button that is in list named buttonList then it gets buttons text. This is code how I make render of those buttons. Its normally in class I put only the main part of code here. So how can I get buttons text on click on him ?
def obsahOkna(self):
#vykresleni
radek = 0
bunka = 0
for i in range(100):
btn = Button(self.okno, text=seznamTextu[i], width="5", height="2", bg="black", command=self.getText)
btn.grid(row=radek, column=bunka)
bunka += 1
if bunka == 10 :
bunka = 0
radek +=1
def getText(self, udalost):
pass
Upvotes: 4
Views: 5631
Reputation: 15226
Ok so here is an example using a class to perform what I think it is you are asking.
You want to use lambda in your command and assign the value of text to a variable. Then you pass that variable to the getTest(self, text)
method to be able to print your button.
From your comment
Whole code is not need i just need way to get buttons text nothing else
I have created a bit of code to illustrate what you are wanting.
EDIT: I have added code that will allow you to change the configs of the button as well.
import tkinter as tk
# created this variable in order to test your code.
seznamTextu = ["1st Button", "2nd Button", "3rd Button", "4th Button", "5th Button"]
class MyButton(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
self.obsahOkna()
def obsahOkna(self):
radek = 0
bunka = 0
for i in range(5):
btn = tk.Button(self.parent, text=seznamTextu[i])
btn.config(command= lambda t=seznamTextu[i], btn = btn: self.getText(t, btn))
# in order for this to work you need to add the command in the config after the button is created.
# in the lambda you need to create the variables to be passed then pass them to the function you want.
btn.grid(row=radek, column=bunka)
bunka += 1
if bunka == 2 : # changed this variable to make it easier to test code.
bunka = 0
radek +=1
def getText(self, text, btn):
btn.configure(background = 'black', foreground = "white")
print("successfully called getText")
print(text)
if __name__ == "__main__":
root = tk.Tk()
myApp = MyButton(root)
root.mainloop()
Here is the result of running the program and pressing a couple buttons.
Upvotes: 4