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
#2
Using functools partial to send a value on a button click
import tkinter as tk
from functools import partial


def button_command(colour):
    print(colour)


root = tk.Tk()

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

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

root.mainloop()


Creating the buttons in a loop

import tkinter as tk
from functools import partial


def button_command(colour):
    print(colour)


root = tk.Tk()

button_colurs = ('red', 'blue', 'green', 'orange')

for button_colour in button_colurs:
    btn = tk.Button(root, text=f"{button_colour} button".capitalize(),
                    bg="white", fg=button_colour,
                    relief="ridge", font="Helvitica 20",
                    command=partial(button_command, button_colour))
    btn.pack()

root.mainloop()
Reply
#3
Thank Yoriz

Partial was something I previously thought I should study and now I have studied it. It may take me a while to try to apply it to the code (which is much more complicated than my example) that I am trying to create.
Reply
#4
partial and lambda should solve all your command callback needs.
Reply
#5
I succeeded in using Partial to select from the menu (see last 2 lines above root.mainloop(). If I select "first color" it prints red and if I select the second color it prints green.

I haven't been successful in capturing "red" or "green" inside a variable outside of the function. Can I do this without using a global variable?

from functools import partial

def mltask (mlvar):
    print (mlvar)
    return mlvar

from tkinter import *
root = Tk()
root.configure(background = 'white')
root.geometry("800x500")

cbutton = Button(root, text="Let's Start", bg="white", \
                        fg="firebrick", relief = "groove", font = "Helvitica 60")
cbutton.pack()

mymenu = Menu(root)
root.config(menu=mymenu)
# Create missing letter easy menu
MLEasyMenu = Menu(mymenu)
mymenu.add_cascade(label = "easy", menu=MLEasyMenu)
MLEasyMenu.add_command(label="firstcolor", command = partial(mltask,'red'))
MLEasyMenu.add_command(label="secondcolor", command= partial(mltask,'green'))

root.mainloop()
Reply
#6
Return on the function mltask won't do anything when called by a GUI event.
The code shown does not give an example of what is meant by capturing "red" or "green" inside a variable outside of the function
Reply
#7
It would be a lot easier to help you if you wrapped you code in python tags
Quote:[python]
# code goes here
[/python]
As for setting variable values, it would be helpful to know what you are trying to do. If you are trying to make a form for entering data, you may want to use tkinter variables and controls that display their value; such as Entry or Checkbutton, Scale, Listbox, etc... This kind of code has only one function callback to process the controls when an Accept button is pressed. If you are writing something with more interaction, you may need to provide a way to store state information. Instead of using a bunch of variables I suggest you read up on Python Classes. Classes are a great way to organize data and functions and work really well when used with GUI interfaces.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tkinter] TKinter Remove Button Frame Nu2Python 8 818 Jan-16-2024, 06:44 PM
Last Post: rob101
  tkinter - touchscreen, push the button like click the mouse John64 5 746 Jan-06-2024, 03:45 PM
Last Post: deanhystad
  Centering and adding a push button to a grid window, TKinter Edward_ 15 4,382 May-25-2023, 07:37 PM
Last Post: deanhystad
  tkinter.TclError: can't invoke "canvas" command cybertooth 8 5,777 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,363 Feb-13-2022, 01:57 PM
Last Post: dford
  [Tkinter] Button 'command' Argument Confusion gw1500se 11 5,691 Nov-11-2021, 08:45 PM
Last Post: menator01
  Creating a function interrupt button tkinter AnotherSam 2 5,418 Oct-07-2021, 02:56 PM
Last Post: AnotherSam
  [Tkinter] Have tkinter button toggle on and off a continuously running function AnotherSam 5 4,920 Oct-01-2021, 05:00 PM
Last Post: Yoriz
  tkinter showing image in button rwahdan 3 5,523 Jun-16-2021, 06:08 AM
Last Post: Yoriz
  Continue command in python tkinter? MLGpotato 7 8,337 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