I am using python 3.11 and Tkinter. I am making a colour palette creator using python and tkinter. I am using a class for the colors in the palette.
Here is my code:
from tkinter import *
import tkinter as tk
import random
hexChars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']
buttonCount = 4
class _Button(Button):
def __init__(self, *args, **kwargs):
Button.__init__(self, args, **kwargs)
self['bg'] = self.rand_hex()
self['text'] = ''
self['image'] = pixel
self['width'] = 55
self['height'] = 55
self['command'] = self.choose_color
self['compound'] = 'c'
Button.pack(self, side=tk.LEFT)
def choose_color(self):
color_code = colorchooser.askcolor(title ="Choose color")
Button.configure(self, bg=color_code[1])
def rand_hex(self):
return '#' + random.choice(hexChars) + random.choice(hexChars) + random.choice(hexChars)
root = Tk()
pixel = tk.PhotoImage(width=1, height=1)
buttons = []
for i in range(buttonCount):
buttons.append(_Button())
root.geometry(str((len(buttons)*61)+32) + "x50")
root.mainloop()
When I run it I get the following error:
Traceback (most recent call last):
File "C:\Users\rufus_tyxwzbt\AppData\Local\Programs\Python\Python311\color_picker.py", line 50, in <module>
buttons.append(_Button())
^^^^^^^^^
File "C:\Users\rufus_tyxwzbt\AppData\Local\Programs\Python\Python311\color_picker.py", line 22, in __init__
Button.__init__(self, args, **kwargs)
File "C:\Users\rufus_tyxwzbt\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py", line 2706, in __init__
Widget.__init__(self, master, 'button', cnf, kw)
File "C:\Users\rufus_tyxwzbt\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py", line 2622, in __init__
self._setup(master, cnf)
File "C:\Users\rufus_tyxwzbt\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py", line 2591, in _setup
self.tk = master.tk
^^^^^^^^^
AttributeError: 'tuple' object has no attribute 'tk'
Can somebody please help
You need to pass *args
, not args
when calling the __init__
method. args
is a tuple, but the first argument needs to be a tkinter widget. That is why you see the error tuple' object has no attribute 'tk'
: widgets have a "tk" attribute but you passed in a tuple.
Button.__init__(self, *args, **kwargs)
# ^^^^^