My tkinter image show up as a black screen - python

I am trying to code a game for my school assignment. In this game, I wanted to have a mute button so I have made a button on top of a label frame and place it in a label. I don't know what is wrong with it but the image does not show up. I have tried to create a local copy by assigning it to a temp variable and yet it still doesn't show up. Here's my code:
from tkinter import ttk
from PIL import Image, ImageTk
root = Tk()
topFrame =Frame(root, width=500, height=50,)
topFrame.grid(row=0, column= 0)
btnframe = LabelFrame(topFrame, width = 20, height = 20)
btnframe.place(x = 450, y= 5 )
mute_image = Image.open("pygame/mute.png")
mute_image = mute_image.resize((50,50), Image.ANTIALIAS)
mute_icon = ImageTk.PhotoImage(mute_image)
mute_button = Button( btnframe, width = 50, height = 50, command = Mute, image = mute_icon)
mute_button.image = mute_icon
mute_button.pack()
root.mainloop()
Please go easy on me, this is my first time coding a game ever:)) Thanks in advance:))

Are you getting any error messages. I slightly modified your code and it complained abuot the button callback function was not defined. After I added that it all seems to work.
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
topFrame =Frame(root, width=500, height=50,)
topFrame.grid(row=0, column= 0)
btnframe = LabelFrame(topFrame, width = 20, height = 20)
btnframe.place(x = 450, y= 5 )
def Mute():
pass
mute_image = Image.open("images/beer.png")
mute_image = mute_image.resize((50,50), Image.ANTIALIAS)
mute_icon = ImageTk.PhotoImage(mute_image)
mute_button = Button(btnframe, width=50, height=50,
command=Mute, image=mute_icon)
mute_button.image = mute_icon
mute_button.pack()
root.mainloop()

Related

Tkinter images and geometry creation

I've tried to do a star fractal drawing a star using tkinter and putting an image as a background.
from tkinter import *
from PIL import ImageTk, Image
import tkinter as tk
app = Tk()
app.title("Welcome")
img =Image.open('C:\\Users\\Stefa\\Downloads\\galaxy.jpeg')
bg = ImageTk.PhotoImage(img)
canvas_width=800
canvas_height=800
master = tk.Tk()
label = Label(app, image=bg)
label.place(x = 0,y = 0)
label2 = Label(app, text = "WELCOME TO OUR GALAXY",
font=("Times New Roman", 24))
label2.pack(pady = 50)
app.geometry(f"{canvas_width}x{canvas_height}")
can_widgt=Canvas(app, width=canvas_width, height= canvas_height)
can_widgt.pack()
points=[200,20,80,396,380,156,20,156,320,396]
can_widgt.create_polygon(points, outline='red',fill='cyan', width=6)
app.mainloop()
That's the code
However when i run it i want the star to be upon the background image. Any solutions for this ? Thanks
You need to create the image as a canvas object rather than as a label.
For example, this add the image to the top-left corner of the canvas, with the drawing on top of it:
can_widgt.create_image(0, 0, anchor="nw", image=bg)

Make tkinter window draw on top of fullscreen applications

I'm wondering if there is a way to draw tkinter windows over fullscreen applications, so far I have this:
from tkinter import *
#MAIN WINDOW
root = Tk()
root.title('Test Title')
root.geometry("500x200")
root.wm_attributes('-transparentcolor', root['bg'])
root.wm_attributes("-topmost", 1)
my_frame = Frame(root, width=500, height=200)
my_frame.pack(pady=20, ipady=20, ipadx=20)
#STAT TEXT
my_label = Label(my_frame, font=("Helvetica", 40), fg="#09d2f6")
my_label.config(text="TEST TEXT")
my_label.pack(pady=20)
root.mainloop()
This draws the window on top of all applications but not fullscreen ones. I had the idea to have a loop where it will constantly bring the window forward but have no idea how to do that.
This code will enable you to choose a picture to view on the fullscreen.
Your code will run in transparent mode above it - no problems
Press Escape key to exit
Try making your widget fullscreen using title button for weird effect!
Had to edit this due to the effect of filedialog on results.
Moved the attribute setting so that it is invoked after image is loaded.
import os
import tkinter as tk
from tkinter import filedialog
def closer( ev ):
ev.widget.destroy()
# FULL SCREEN
master = tk.Tk()
master.rowconfigure( 0, weight = 1 )
master.columnconfigure( 0, weight = 1 )
master.bind( "<Escape>", closer )
pathfile = filedialog.askopenfilename( title = 'pick mage' )
my_image = tk.PhotoImage( file = pathfile ).zoom( 2,2 )
label = tk.Label( master, text = 'Image', compound = "top", image = my_image )
label.grid(row=0, column=0,sticky='nsew')
master.wm_attributes("-fullscreen", 1)
# removed for first time use - unrem this for second time
# master.wm_attributes("-topmost", 1)
# Your code
root = tk.Toplevel(master)
root.title('Test Title')
root.geometry("500x200")
root.bind( "<Escape>", closer )
root.wm_attributes('-transparentcolor', root['bg'])
root.wm_attributes("-topmost", 1)
my_frame = tk.Frame(root, width=500, height=200)
my_frame.pack(pady=20, ipady=20, ipadx=20)
#STAT TEXT
my_label = tk.Label(my_frame, font=("Helvetica", 40), fg="#09d2f6")
my_label.config(text="TEST TEXT")
my_label.pack(pady=20)
master.mainloop()

Buttons getting misplaced after using background image in Tkinter

Whenever I run this code with a background Image the button grid gets misplaced and pushed towards the bottom. Fortunately, it works as intended when no background is added .I want them to cover the background when executed. Pictures for reference are added below. Your help is highly appreciated.
# importing the module
import tkinter.messagebox
from tkinter import *
import random
# 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("630x630")
root.title('Odd Even Game')
C = Canvas(root, bg="blue", height=250, width=300)
filename = PhotoImage(file = "BG.png")
background_label = Label(root,image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
C.pack()
frame = Frame(root)
frame.pack()
# creating the window
# image
level_1e = "p1.png"
level_1o = "pe.png"
level_2e = "r1.png"
level_2o = "re.png"
# image
def create_cards(odd_image,even_image,next_level,fno,order,suc,err,w,h):
rx = random.randint(0,order-1)
ry = random.randint(0,order-1)
for i in range(0,order):
for j in range(0,order):
if i == rx and j == ry:
create_button(i,j,suc,odd_image,next_level,fno,odd_image,w,h)
else:
create_button(i,j,err,even_image,next_level,fno,odd_image,w,h)
def second_level(fno):
fno.pack_forget()
frame2 = Frame(root)
frame2.pack()
suc = "Congratulations! You have cleared level 2..Keep Going Buddy!"
err = "Wrong Answer..Don't give up yet!"
create_cards(level_2o,level_2e,final_level,frame2,4,suc,err,157.5,157.5)
def final_level(fno):
fno.pack_forget()
root.geometry("700x700")
ap = App(root)
# creating a button function
def create_button(x,y,msg,picture,next_level,fno,odd,w,h):
if picture == odd:
image = PhotoImage(file=picture)
click = Button(fno, image=image, width= w, height=h, bd = 0,command = lambda : [score_update(),next_level(fno),tkinter.messagebox.showinfo( "Odd One Out Project",msg)])
click.image = image
click.grid( row = x, column = y)
else:
image = PhotoImage(file=picture)
click = Button(fno, image=image, width= w, height=h, bd = 0,command = lambda : [next_level(fno),tkinter.messagebox.showinfo( "Odd One Out Project",msg)])
click.image = image
click.grid( row = x, column = y)
# creating a button function
def create_frame(fno):
root.geometry("630x630")
fno.pack_forget()
frame = Frame(root)
frame.pack()
suc = "Congratulations! You have cleared level 1..Time to increas[![enter image description here][1]][1]e the difficulty!"
err = "Wrong Answer..Please Try again !!"
create_cards(level_1o,level_1e,second_level,frame,3,suc,err,200,200)
def intro():
root.geometry("630x630")
frame0 = Frame(root)
frame0.pack()
click = Button(frame0,text="Start!" ,command = lambda [create_frame(frame0),tkinter.messagebox.showinfo( "Odd One Out Project","The game has begun!!")])
click.pack()
intro()
# starting the widget
root.mainloop()
# starting the widget
The first image is the error. Second Image is the required output.
Note: I'm still a beginner in Python and Tkinter hence various terms and methods might be something out of my scope. Would be appreciated if taken into consideration.
In case needed, you might know that this is a tkinter project for picking the odd one out image out of A*A grid.
I got the answer myself so will be sharing for future use.
C = Canvas(root, bg="blue", height=250, width=300)
This part draws a canvas of 250*300 dimensions hence does not let the buttons draw over it.
just change it to,
C = Canvas(root, bg="blue", height=0, width=0)
for the desired result

Canvas won't show a PhotoImage pic if the code is in a method

New to python and so far mostly love it but this issue is odd. The exact same code works from the root but not in a method.
This does not render the image:
from tkinter import *
root = Tk()
def draw():
print("does not work")
canvas = Canvas(root, width = 300, height = 300)
canvas.pack()
img = PhotoImage(file="Db.png")
canvas.create_image(20,20, anchor=NW, image=img)
draw()
mainloop()
But this works fine:
from tkinter import *
root = Tk()
print("This works fine")
canvas = Canvas(root, width = 300, height = 300)
canvas.pack()
img = PhotoImage(file="Db.png")
canvas.create_image(20,20, anchor=NW, image=img)
mainloop()
Any help would be appreciated.
As martineau explains in the comments above the problem with the code is that the img variable only exists while the function is processing, it is deleted after the function returns and it's required that I keep a reference to the image object. Making it a global variable corrects the issue.
Many Thanks!

StringVar.set("...") does not work in multiple tkinter windows

My program has a library which opens a new window
This is the library (its called make_entry):
from tkinter import *
def Create():
Window = Tk() # window
Window.geometry("900x500+50+50") # heightxwidth+x+y
mainPanel = Canvas(Window, width = 900, height = 500) # main screen
mainPanel.pack()
anyvar = StringVar() # the text in the entry
entry = Entry(mainPanel, width = 40, font = ("Purisa", 12, "bold"), justify = "center", textvariable = anyvar) # the entry
mainPanel.create_window(200, 100, window = entry)
anyvar.set("This doesnt work!!!!!")
Window.mainloop()
#Create()
If I run this library by itself then everything works fine, but when I import it from another program the only thing which doesn't work is anyvar.set("This doesnt work!!!!!").
Here is where I import it: (most of this code is cut out)
from tkinter import *
Window = Tk()
import make_entry
make_entry.Create()
Window.mainloop()
Is there a way to fix this problem without removing any of the windows?
You have two instances of Tk() which confuses Tkinter. I am guessing that the StringVar() is going to the other (first) instance. Instead, pass the only instance to the function, and use a Toplevel for a new window.
from tkinter import *
def Create(root):
window=Toplevel(root)
window.geometry("900x500+50+50") # heightxwidth+x+y
mainpanel = Canvas(window, width = 900, height = 500) # main screen
mainpanel.pack()
anyvar = StringVar() # the text in the entry
entry = Entry(mainpanel, width = 40, font = ("Purisa", 12, "bold"), justify = "center", textvariable = anyvar) # the entry
mainpanel.create_window(200, 100, window = entry)
anyvar.set("This doesnt work!!!!!")
and
from tkinter import *
Window = Tk()
import make_entry
make_entry.Create(Window)
Window.mainloop()

Categories

Resources