-1

I have a button that calls a function that asks the user to select a colour. The problem is the colour selection window gets called immediately and the button doesn't work after you input something into the window.

import tkinter as tk
from tkinter.colorchooser import askcolor

main = tk.Tk()

def color_picker(type):
  color = askcolor(title = 'choose ' + type + ' color')
  return color

track_color = tk.Button(main, text='chose track color', command = color_picker('track'))
track_color.pack()

try :
  main()
except TypeError:
  pass

I have no idea why this happens as the function, in theory, is only called when the button is pressed.

Tkinter Lover
  • 835
  • 3
  • 19

1 Answers1

1

Since you have parenthesis on your function, it gets called before the color is chosen. To prevent this, use lambda.

So replace line 10 with track_color = tk.Button(main, text='chose track color', command = lambda: color_picker('track')).

Your new code:

import tkinter as tk
from tkinter.colorchooser import askcolor

main = tk.Tk()


def color_picker(type):
  color = askcolor(title = 'choose ' + type + ' color')


track_color = tk.Button(main, text='chose track color', command = lambda: color_picker('track'))
track_color.pack()

main.mainloop()
Tkinter Lover
  • 835
  • 3
  • 19