Custom Tkinter Images - python

I'm trying to create a back button. I have an image called back-button.png in the folder img.
This is my code:
from tkinter import *
import customtkinter as ctk
root = Tk()
ctk.CTkLabel(root,
text = 'This is a label',
text_font =('Verdana', 17)).pack(side = LEFT, pady = 11)
img = PhotoImage(file="./img/back-button.png")
ctk.CTkButton(root, image = img).pack(side = LEFT)
root.mainloop()
When I run this code I get this error:
Traceback (most recent call last):
File "c:\Users\User\Desktop\youtube-audio-downloader\tempCodeRunnerFile.py", line 11, in <module>
ctk.CTkButton(root, image = img).pack(side = LEFT)
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\customtkinter\customtkinter_button.py", line 102, in __init__
self.draw()
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\customtkinter\customtkinter_button.py", line 147, in draw
self.canvas.configure(bg=CTkColorManager.single_color(self.bg_color, self.appearance_mode))
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1646, in configure
return self._configure('configure', cnf, kw)
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1636, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: unknown color name "."
So, why is this happening? And how can I display an image on a button?

The problem is that the CtkButton widget doesn't not accept parameters the same way as standard widgets. The first parameter to a CtkButton is the background color, but you're passing the root window and the root window isn't a valid color.
You need to explicitly assign the root window to the master argument.
ctk.CTkButton(master=root, image = img).pack(side = LEFT)
# ^^^^^^^

You are getting error because you are using built-in image define method which is in Tkinter not in Customtkinter. Don't confuse these two. If you want to use Customtkinter only use that because when you are making bigger projects than this, it will be a whole mess if you use these two together.
import customtkinter
from PIL import Image, ImageTk
window = customtkinter.CTk()
button_image = customtkinter.CTkImage(Image.open("assets/yourimage.png"), size=(26, 26))
image_button = customtkinter.CTkButton(master=window, text="Text will be gone if you don't use compound attribute",image=button_image)
image_button.pack()
window.mainloop()

Related

_str__ returned non-string (type JpegImageFile) While trying to use image as button in tkinter python

_str__ returned non-string (type JpegImageFile) while trying to use image as button in Tkinter. I tried file= instead of Image.open but that didn't work too. Can someone tell me how to fix this
Here is the simplified version of the code:
from tkinter import *
from PIL import ImageTk, Image
# Window setup
mainwindow = Tk()
mainwindow.geometry('420x420')
mainwindow.title('Root Screen')
# Button image source
temp_img = PhotoImage(Image.open('D:\\Coding\\Python_stuff\\Watch_T800\\temp_img.jpg'))
temp_img_lbl = Label(image=temp_img)
temp_img_lbl.pack()
# Button function
def menufun():
menuwindow = Tk()
menuwindow.geometry('420x420')
menuwindow.title('Menu')
temp = Button(menuwindow, text="Temperature",height=5, width=10, image=temp_img)
temp.grid(row=0, column=0)
# Home Buttons
menu = Button(mainwindow, text="Menu", command=menufun).pack()
# BG Image
bg=Image.open('D:\\Coding\\Python_stuff\\Watch_T800\\background.png')
blah1=ImageTk.PhotoImage(bg)
lbl=Label(mainwindow, image=blah1)
lbl.pack()
mainloop()
And here is the error:
Traceback (most recent call last):
File "d:\Coding\Python_stuff\Watch_T800\test.py", line 14, in <module>
temp_img_lbl = Label(image=temp_img)
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\yashw\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py", line 3204, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Users\yashw\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py", line 2628, in __init__
self.tk.call(
TypeError: __str__ returned non-string (type JpegImageFile)
I already explained what I tried in the , But I'm telling it again
I have tried using file= instead of image.open but it says
Pyimage1 Not found

Images not showing up in tkinter GUI window

Basically I'm having trouble opening images (.jpg) in a tkinter GUI window.
I followed this tutorial: https://www.youtube.com/watch?v=lt78_05hHSk
But I just get a blank window.
from tkinter import *
root = Tk()
photo = PhotoImage(file=r"C:\Users\xxxx\OneDrive\Desktop\123k.jpg")
# photo = PhotoImage(file="123k.jpg")
label = Label(root, image=photo)
label.pack()
root.mainloop()
The file path is correct and .jpg files are compatible with tkinter. What could be going on?
I get this error
Traceback (most recent call last):
File "C:\Users\xxx\ytrewq.py", line 5,
in <module> photo = PhotoImage(file=r"C:\Users\xxxx\OneDrive\Desktop\123k.jpg")
File "C:\Users\xxxx\AppData\Local\Programs\Thonny\lib\tkinter_init_.py", line 3545,
in init Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Users\xxxx\AppData\Local\Programs\Thonny\lib\tkinter_init_.py", line 3501,
in init self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file
"C:\Users\xxxx\OneDrive\Desktop\123k.jpg"
This error occurs because only PhotoImage function can't recognize the .jpg formate image. For this, you could use png formate or you could use
Image.open(path_of_the_file) and then
ImageTk.PhotoImage(img_object)
for this Image and ImageTk you have to import this from PIL module
from PIL import Image, ImageTk
The hole solution code:
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
# photo = PhotoImage(file=r"C:\Users\xxxx\OneDrive\Desktop\123k.jpg")
# photo = PhotoImage(file="123k.jpg")
img = Image.open(file=r"C:\Users\xxxx\OneDrive\Desktop\123k.jpg")
photo = ImageTk.PhotoImage(img)
label = Label(root, image=photo)
label.pack()
root.mainloop()

Tkinter Label image setting won´t work

I've been learning how to use Tkinter from scratch and while I try to set a simple Label widget in a frame:
from Tkinter import *
from ttk import *
root = Tk()
root.title("Practice")
mainW = LabelFrame(root, text = "Main info")
mainW.grid()
image = Label(mainW, image = "C:\Users\Oscar Ramirez\Pictures\image.png")
image.grid(column = 0, row = 0)
codeEntry = Entry(mainW, text = "User Code")
codeEntry.grid(column = 1, row = 0)
root.mainloop()
I'm getting the following error:
Traceback (most recent call last):
File "Tutorial.py", line 10, in <module>
image = Label(mainW, image = "C:\Users\Oscar Ramirez\Pictures\image.png")
File "C:\Python27\lib\lib-tk\ttk.py", line 757, in __init__
Widget.__init__(self, master, "ttk::label", kw)
File "C:\Python27\lib\lib-tk\ttk.py", line 555, in __init__
Tkinter.Widget.__init__(self, master, widgetname, kw=kw)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 2096, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image specification must contain an odd number of elements
I've checked the image format, the route, etc. And now I don't really know what can be causing me trouble.
image
The image to display in the widget. The value should be a
PhotoImage, BitmapImage, or a compatible object. If specified, this
takes precedence over the text and bitmap options. (image/Image)
Right now you are just passing a string for image option of label. You need something like,
photo = PhotoImage(file="image.gif")
label = Label(..., image=photo)
label.photo = photo #reference keeping is important when working with images
Right now, since you are using PNG image, you need to install and use Python Imaging Library (PIL) though. For more info, you can read Photo Image section from effbot.

Huge error message when using .config

I'm trying to learn tkinter and am making a calculator.
I am setting up the buttons and am now trying to change the size of one of them with:
Button_back = ttk.Button(Frame1, text='Back', command=printhi) #printhi is temporary.
Button_back.grid(column=0, row=0)
Button_back.config( height = 25, width = 25 )
When I try run it the error message is:
>Traceback (most recent call last): File "C:\Users\Luuk\Python
>PGMs\tkinter\2-1 - Calculator.py", line 75, in <module>
>Button_back.config( Height = 25, width = 25 )
>File "C:\Program Files (x86)\Python34\lib\tkinter\__init__.py", line 1270, in configure
>return self._configure('configure', cnf, kw) File "C:\Program Files (x86)\Python34\lib\tkinter\__init__.py", line 1261, in
> _configure
>self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
> _tkinter.TclError: unknown option "-height"
I have no idea what I'm doing wrong here, as per every webpage this is what should handle the width and height correctly
Your answer is half right...but there is a height option for a Tkinter Button, just not a ttk Button. If you absolutely need the height option, you can still use a regular Tkinter button, it just won't be as pretty. Also, you can print the dictionary of widget options if you're ever in this bind again by printing widget.config().
import tkinter as tk
import ttk
root = tk.Tk()
tk_button = tk.Button(root, text='tkinter button')
ttk_button = ttk.Button(root, text='ttk button')
for key in tk_button.config().iterkeys():
print('tkinter: ' + key)
for key in ttk_button.config().iterkeys():
print('ttk: ' + key)
tk_button.pack()
ttk_button.pack()
root.mainloop()
There is no such thing as 'height' for a button, only width... (Also for other things probably but this is what I know for sure now)
Found this after another half hour search:
http://www-acc.kek.jp/WWW-ACC-exp/KEKB/control/Activity/Python/TkIntro/introduction/button.htm

How do I change the background of a Frame in Tkinter?

I have been creating an Email program using Tkinter, in Python 3.3.
On various sites I have been seeing that the Frame widget can get a different background using Frame.config(background="color").
However, when I use this in my Frames it gives the following error:
_tkinter.TclError: unknown option "-Background"
It does not work when doing the following:
frame = Frame(root, background="white")
Or:
frame = Frame(root)
frame.config(bg="white")
I can't figure it out.
I would post my whole source code but I dont want it exposed on the internet, but the frame creation goes something like this:
mail1 = Frame(self, relief=SUNKEN)
mail1.pack()
mail1.place(height=70, width=400, x=803, y=109)
mail1.config(Background="white")
I have tried multiple options trying to modify the background. The frame is like a wrap around an email preview for an inbox.
In case it's needed, this the way I am importing my modules:
import tkinter, time, base64, imaplib, smtplib
from imaplib import *
from tkinter import *
from tkinter.ttk import *
The following is the full traceback:
Traceback (most recent call last):
File "C:\Users\Wessel\Dropbox\Python\Main\Class Ginomail.py", line 457, in <module>
main()
File "C:\Users\Wessel\Dropbox\Python\Main\Class Ginomail.py", line 453, in main
app = Application(root) #start the application with root as the parent
File "C:\Users\Wessel\Dropbox\Python\Main\Class Ginomail.py", line 60, in __init__
self.initINBOX()
File "C:\Users\Wessel\Dropbox\Python\Main\Class Ginomail.py", line 317, in initINBOX
mail1.config(bg="white")
File "C:\Python33\lib\tkinter\__init__.py", line 1263, in configure
return self._configure('configure', cnf, kw)
File "C:\Python33\lib\tkinter\__init__.py", line 1254, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: unknown option "-bg"
Gives the following error with the code from the answer:
File "C:\Users\Wessel\Dropbox\Python\Main\Class Ginomail.py", line 317, in initINBOX
mail1 = Frame(self, relief=SUNKEN, style='myframe')
File "C:\Python33\lib\tkinter\ttk.py", line 733, in __init__
Widget.__init__(self, master, "ttk::frame", kw)
File "C:\Python33\lib\tkinter\ttk.py", line 553, in __init__
tkinter.Widget.__init__(self, master, widgetname, kw=kw)
File "C:\Python33\lib\tkinter\__init__.py", line 2075, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: Layout myframe not found
Solved! Thanks. Its the inbox bar to the right, background needed to be white.
The root of the problem is that you are unknowingly using the Frame class from the ttk package rather than from the tkinter package. The one from ttk does not support the background option.
This is the main reason why you shouldn't do wildcard imports -- you can overwrite the definition of classes and commands.
I recommend doing imports like this:
import tkinter as tk
import ttk
Then you prefix the widgets with either tk or ttk :
f1 = tk.Frame(..., bg=..., fg=...)
f2 = ttk.Frame(..., style=...)
It then becomes instantly obvious which widget you are using, at the expense of just a tiny bit more typing. If you had done this, this error in your code would never have happened.
You use ttk.Frame, bg option does not work for it. You should create style and apply it to the frame.
from tkinter import *
from tkinter.ttk import *
root = Tk()
s = Style()
s.configure('My.TFrame', background='red')
mail1 = Frame(root, style='My.TFrame')
mail1.place(height=70, width=400, x=83, y=109)
mail1.config()
root.mainloop()

Categories