How to pass an argument to the onclick function when you click a button on Python. GUI writing on Tkinter

    2 answers 2

    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()