How to pass an argument to the onclick function when you click a button on Python. GUI writing on Tkinter
2 answers
from tkinter import * def foo(event): # Π€ΡΠ½ΠΊΡΠΈΡ Π΄Π»Ρ ΠΊΠ½ΠΎΠΏΠΊΠΈ 'event' ΠΎΠ±ΡΠ·Π°ΡΠ΅Π»ΡΠ½ΡΠΉ ΠΏΠ°ΡΠ°ΠΌΠ΅ΡΡ print('Hello World!') print(entry.get()) root = Tk() # Π‘ΠΎΠ·Π΄Π°ΡΠΌ ΠΎΠΊΠ½ΠΎ btn = Button(root, text='Print') # Π‘ΠΎΠ·Π΄Π°ΡΠΌ ΠΊΠ½ΠΎΠΏΠΊΡ entry = Entry(root) entry.pack() btn.pack() # ΠΡΠΎΠ±ΡΠ°ΠΆΠ°Π΅ΠΌ ΠΊΠ½ΠΎΠΏΠΊΡ btn.bind('<Button-1>', foo) # ΠΠ΅ΡΠ΅Π΄Π°Π΅ΠΌ ΡΡΠ½ΠΊΡΠΈΡ ΠΏΡΠΈ Π½Π°ΠΆΠ°ΡΠΈΠΈ ΠΊΠ½ΠΎΠΏΠΊΠΈ root.mainloop() # ΠΡΠΎΠ±ΡΠ°ΠΆΠ°Π΅ΠΌ ΠΎΠΊΠ½ΠΎ - I need not just to use functions when pressed, but to pass an argument to a function, for example, that when the button is pressed, the function foo (arg) is heard, where the arg is my number or string - Oleg_Hudyma
- You need to create a field and enter data into it, and then output it. Corrected the answer - Pavel Durmanov
- In general, I have a class where there is a list of buttons and a form for entering strings, there are functions delete (btn), which takes in the arguments of the name of the button that was clicked. That is, when you press the btn3 button, the function delete (bnt3) - Oleg_Hudyma
- @Oleg_Hudyma you can
lambda: delete(bnt3)explicitly pass or calculate from context if it is more appropriate for you. Update your question and provide a complete, but minimal example of code that shows your case (you donβt need to include everything) βIf you can explain the essence of the problem with one button, then use only one, etc. - jfs
|
from tkinter import * def delete_widget(event): event.widget.destroy() root = Tk() buts = [] for i in range(3): buts.append(Button(root, text = "Delete me!")) buts[i].pack() buts[i].bind("<Button-1>", delete_widget) root.mainloop() |