Python Forum
[Tkinter] button command tkinter
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] button command tkinter
#1
Hello Python Users:

The following is a simple Python program. If you press the button with label red it prints "red". If you press the button with label blue it prints "blue".

One thing that frustrates me is that I have to write a function for every button. If I have 20 buttons I need 20 funcitons.

What I would like to do is have the same function for every button. Then using an "IF" statement it would print red if the red button was pressed and blue if the blue button was pressed. This would greatly simplify my code. Any suggestions?

def red():
    print("red")

def blue():
    print("blue")

red = Button(root, text="Red button", bg="white", fg="red",relief = "ridge", font = "Helvitica 20", command=red)
red.pack()

blue = Button(root, text="blue button", bg="white", fg="blue", relief = "groove",font = "Helvitica 20",command = blue)
blue.pack()

root.mainloop()
Reply


Messages In This Thread
button command tkinter - by Heyjoe - Jul-23-2020, 05:46 PM
RE: button command tkinter - by Yoriz - Jul-23-2020, 06:01 PM
RE: button command tkinter - by Heyjoe - Jul-24-2020, 12:55 AM
RE: button command tkinter - by deanhystad - Jul-26-2020, 06:20 PM
RE: button command tkinter - by Heyjoe - Jul-30-2020, 06:37 PM
RE: button command tkinter - by Yoriz - Jul-30-2020, 06:51 PM
RE: button command tkinter - by deanhystad - Jul-30-2020, 07:06 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tkinter] TKinter Remove Button Frame Nu2Python 8 1,012 Jan-16-2024, 06:44 PM
Last Post: rob101
  tkinter - touchscreen, push the button like click the mouse John64 5 869 Jan-06-2024, 03:45 PM
Last Post: deanhystad
  Centering and adding a push button to a grid window, TKinter Edward_ 15 4,861 May-25-2023, 07:37 PM
Last Post: deanhystad
  tkinter.TclError: can't invoke "canvas" command cybertooth 8 6,023 Feb-23-2023, 06:58 PM
Last Post: deanhystad
  Can't get tkinter button to change color based on changes in data dford 4 3,437 Feb-13-2022, 01:57 PM
Last Post: dford
  [Tkinter] Button 'command' Argument Confusion gw1500se 11 5,895 Nov-11-2021, 08:45 PM
Last Post: menator01
  Creating a function interrupt button tkinter AnotherSam 2 5,562 Oct-07-2021, 02:56 PM
Last Post: AnotherSam
  [Tkinter] Have tkinter button toggle on and off a continuously running function AnotherSam 5 5,030 Oct-01-2021, 05:00 PM
Last Post: Yoriz
  tkinter showing image in button rwahdan 3 5,649 Jun-16-2021, 06:08 AM
Last Post: Yoriz
  Continue command in python tkinter? MLGpotato 7 8,491 Mar-27-2021, 04:59 AM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020