So I want to use an image as my background in Tkinter kind of like how windows has background images in desktop. This is my code but it doesn't seem to work:
root = tk.Tk()
root.attributes("-fullscreen", True)
background_image=tk.PhotoImage("image")
The code runs but it shows up as a white background.
It is pretty simple! Here is how to do it:
from tkinter import *
root = Tk()
root.geometry("400x400")
bg = PhotoImage(file = "image.png")
label1 = Label(root, image = bg)
label1.place(x = 0, y = 0)
root.mainloop()
Just make sure to edit this part (file = "image.png") and use the pathname to your image. Preferably save it on the same folder as your program is stored, though it is not required.
Related
Could you help me? I'm trying to close my main window and then create a new window. I'm using withdraw() instead of destroy() since I'm planning to use that widget later.
Here is my code, but I just get: tkinter.TclError: image "pyimage10" doesn't exist
I separated the codes of the main window and a new window into two python file, which are "Page1" and "Page2".
Sorry for my rough English.
Any help to fix this would be much appreciated:)
tkinter.TclError: image "pyimage10" doesn't existseems to occur at image_2 = canvas.create_image(
Page1
from tkinter import Tk, Canvas, Entry, Text, Button, PhotoImage
OUTPUT_PATH = Path(__file__).parent
ASSETS_PATH = OUTPUT_PATH / Path("./assets")
def relative_to_assets(path: str) -> Path:
return ASSETS_PATH / Path(path)
window = Tk()
window.geometry("703x981")
window.configure(bg = "#FFFFFF")
button_image_6 = PhotoImage(
file=relative_to_assets("button_6.png"))
button_6 = Button(
image=button_image_6,
borderwidth=0,
highlightthickness=0,
command=lambda: ("WM_DELETE_WINDOW", nextPage()),
relief="flat"
)
button_6.place(
x=415.0,
y=793.0,
width=86.0,
height=78.0
)
def nextPage():
window.withdraw()
import Page2
Page2
from tkinter import Tk, Canvas, Entry, Text, Button, PhotoImage
window = Tk()
def relative_to_assets(path: str) -> Path:
return ASSETS_PATH / Path(path)
window.geometry("545x470")
window.configure(bg = "#FFFFFF")
window.title('PythonGuides')
canvas = Canvas(
window,
bg = "#FFFFFF",
height = 470,
width = 545,
bd = 0,
highlightthickness = 0,
relief = "ridge"
)
canvas.place(x = 0, y = 0)
image_image_2 = PhotoImage(
file=relative_to_assets("image_2.png"))
image_2 = canvas.create_image(
272.0,
175.0,
image=image_image_2
)
Maybe it's happening because the image you are trying to add on the button is not present where you are trying to access it from.
And seems you have missed this:
You didn't pack the button
You didn't run the .mainloop() i.e window.mainloop()
and what does the :
[enter the image description here][1]
is meant to do ?
I didn't use this and the code ran perfectly fine.
This error is caused by having multiple instances of Tk. Having multiple instances of Tk can cause errors. Use Toplevel instead for additional windows.
Change window = Tk() to window = Toplevel() in Page2. You will also need to add Toplevel to your import list.
i wrote this code on the school computer, and it was totally fine. i wrote the same code on my personal pc and now it shows the picture with no transparency (with black background). the picture is the same picture(a png with no background)
from tkinter import *
from PIL import ImageTk, Image
root = Tk()
root.geometry("1300x731")
root.resizable(width=False, height=False)
photo = Image.open("logo.png")
zoom = 0.5
pixels_x, pixels_y = tuple([int(zoom * x) for x in photo.size])
img = ImageTk.PhotoImage(photo.resize((pixels_x, pixels_y)))
panel = Label(root, image = img).place(relx = 0.5, rely = 0.1, anchor = 'center')
#panel.grid(row=5000, column=3)
#panel.pack(side = "bottom", fill = "both", expand = "yes")
root.config(cursor="#curs.cur")
while True:
root.mainloop()
try it with another import method.
use photo = PhotoImage(file="logo.png")
this should remove the black background.
Remove the "while True:"
root.mainloop() is a loop by itself
The following project is supposed to show a message when clicking a certain colored button. But, whenever I execute the program it shows blank(white) buttons in the correct alignment, etc. Due to some reason the images are not loaded.
In future, I plan to add different images hence testing with colored image created in Paint and not in-built commands to show the color.
I will add the result below after the code.
Edit: All images are 100x100 pixels created in Microsoft Paint.I have tried other modules like PIL but to no avail.
# importing the module
import tkinter
import tkinter.messagebox
from tkinter import *
# importing the module
# initialising tkinter
class window(Frame):
def __init__(self,master = None):
Frame.__init__(self,master)
self.master = master
# initialising tkinter
# creating the window
root = Tk()
app = window(root)
root.geometry("350x350")
# creating the window
# colours
WHITE = (255,255,255)
BLACK = (0,0,0)
BLUE = (0,0,255)
RED = (255,0,0)
# colours
# image
red_image = "red.png"
blue_image = "blue.png"
yellow_image = "yellow.png"
green_image = "green.png"
# image
# creating a button function
def create_button(x,y,color,color2,picture):
click = Button(root, image = PhotoImage(picture), width= 150, height=150, command = lambda : tkinter.messagebox.showinfo( "Hello Python", "This is " + color))
click.image = PhotoImage(picture)
click.grid( row = x, column = y)
# creating a button function
create_button(0,0,'red','pink',red_image)
create_button(0,2,'blue','lightblue',blue_image)
create_button(2,0,'green','lightgreen',green_image)
create_button(2,2,'yellow','lightyellow',yellow_image)
# starting the widget
root.mainloop()
# starting the widget
There are two issues in your code:
You passed filename to PhotoImage() without using file keyword: PhotoImage(picture) should be PhotoImage(file=picture)
You did not keep the reference of the image assigned to button, but another instance of image
Below is the updated create_button() function that fixes the issues:
def create_button(x, y, color, color2, picture):
image = PhotoImage(file=picture)
click = Button(root, image=image, width=150, height=150, command=lambda: tkinter.messagebox.showinfo("Hello Python", "This is "+color))
click.image = image
click.grid(row=x, column=y)
For adding image in Button you have not use appropriate keywords.
Here is a simple example for you to add image in button
from tkinter import *
from tkinter.ttk import *
# creating tkinter window
root = Tk()
# Adding widgets to the root window
Label(root, text = 'Image adding', font =( 'Verdana',15)).pack(side = TOP, pady = 10)
# Creating a photoimage object to use image
photo = PhotoImage(file = "C:\Gfg\circle.png")
# here, image option is used to
# set image on button
Button(root, text = 'Click Me !', image = photo).pack(side = TOP)
root.mainloop()
I think it may help you
I've been working to get a simple Tkinter canvas to display an image using create_image. I've read many threads that say that you need to create a reference to the object outside any function or class, otherwise the image object will be garbage collected. Unfortunately, I still cannot get this to work. Below is my code as it stands. Ignore all the colors - I use them to illustrate where the frames and canvas live on the window.
-Kirk
import Tkinter as tk
from PIL import Image
from PIL import ImageTk
imageList = []
image = Image.open('len_std.jpg')
#event handlers
def hit_sel_click():
imageList = []
test_image = ImageTk.PhotoImage(image)
imageList.append(cnv_hits.create_image(0,0,
image=test_image))
#start root
root = tk.Tk()
root.title('SimView')
root.resizable(width=False, height=False)
#target/control variables
hit_sel = tk.StringVar() #holds radio button with activity level
#build GUI
frm_hits = tk.Frame(root, height=800, width=200, bg='#FF0000')
frm_hits.grid(rowspan=3, sticky=tk.W+tk.N+tk.S+tk.E)
tk.Label(frm_hits, text='Activity:').grid()
tk.Radiobutton(frm_hits, text='Low', variable=hit_sel, value='Low',
command=hit_sel_click).grid(sticky=tk.W)
tk.Radiobutton(frm_hits, text='Medium', variable=hit_sel, value='Medium',
command=hit_sel_click).grid(sticky=tk.W)
tmp = tk.Radiobutton(frm_hits, text='High', variable=hit_sel,value='High',
command=hit_sel_click)
tmp.grid(sticky=tk.W)
tmp.select()
frm_hit_list = tk.Frame(frm_hits, bg='#002288')
frm_hit_list.grid(sticky=tk.W+tk.N+tk.E+tk.S)
scrl_hits = tk.Scrollbar(frm_hit_list, orient=tk.VERTICAL)
scrl_hits.grid(row=0, column=1, sticky=tk.N+tk.S)
cnv_hits = tk.Canvas(frm_hit_list, bg='#888800',width=200, height=200,
yscrollcommand=scrl_hits.set)
cnv_hits.grid(row=0, column=0, sticky=tk.W+tk.N+tk.E+tk.S)
scrl_hits.config(command=cnv_hits.yview)
root.mainloop()
You are using test_image to draw the image of cnv_hits. That is right, but you forgot that test_image is local to hit_sel_click() method; which thing means it is not available to your main program.
To resolve this, you have 2 choices:
Either declare test_image as global inside hit_sel_click()
Or run test_image = ImageTk.PhotoImage(image) before you declare hit_sel_click().
Nota Bene:
For the first case, you will need to run root = tk.Tk() before hit_sel_click().
In case you choose the second option, you will need to run root = tk.Tk() before test_image = ImageTk.PhotoImage(image)
If you don't do this, your program will raise a RuntimeError exception.
I am trying to implement a button that has transparency using PIL and reading a PNG with transparency. I've followed all the tips I can find, but the button still shows up without transparency.
Screenshot of button in GIMP
Screenshot of Python output
Here is the code:
from Tkinter import *
from PIL import Image, ImageTk
root = Tk()
root.resizable(width=FALSE, height = FALSE)
global background, redbutton, rb1
rb1 =ImageTk.PhotoImage(file="test.png")
#confirm the png file is correct format
im = Image.open("test.png")
print im.mode
bg = PhotoImage(file = "background.gif")
GameWin = Canvas(root, bd = 2, height = 600, width = 450)
GameWin.create_image(0,0, image = bg, anchor = NW)
rb = Button(GameWin, bd=0, image=rb1)
# create a window in the canvas for the button
rb_win = GameWin.create_window(10, 10, anchor=NW, window=rb)
GameWin.pack()
root.mainloop()
Putting a window onto the canvas overwrites the background image. If I create_image in the canvas, I can correctly put the image of the button on the canvas (with transparency), but not an actual Button widget. My next step is to learn how to have the image react to mouseclicks so I can emulate some basic Button functionality.