Image in tkinter window by clicking on button - python

I need help about this program, this program should open image in new tkinter window by clicking on button, but it doesn't it just opens new window without image.
Where is the problem?
Using: python 3.3 and tkinter
This is program:
import sys
from tkinter import *
def button1():
novi = Toplevel()
canvas = Canvas(novi, width = 300, height = 200)
canvas.pack(expand = YES, fill = BOTH)
gif1 = PhotoImage(file = 'image.gif')
canvas.create_image(50, 10, visual = gif1, anchor = NW)
mGui = Tk()
button1 = Button(mGui,text ='Sklop',command = button1, height=5, width=20).pack()
mGui.mainloop()

create_image needs a image argument, not visual to use the image, so instead of visual = gif1, you need image = gif1. The next problem is that you need to store the gif1 reference somewhere or else it'll get garbage collected and tkinter won't be able to use it anymore.
So something like this:
import sys
from tkinter import * #or Tkinter if you're on Python2.7
def button1():
novi = Toplevel()
canvas = Canvas(novi, width = 300, height = 200)
canvas.pack(expand = YES, fill = BOTH)
gif1 = PhotoImage(file = 'image.gif')
#image not visual
canvas.create_image(50, 10, image = gif1, anchor = NW)
#assigned the gif1 to the canvas object
canvas.gif1 = gif1
mGui = Tk()
button1 = Button(mGui,text ='Sklop',command = button1, height=5, width=20).pack()
mGui.mainloop()
It's also probably not a good idea to name your Button the same name as the function button1, that'll just cause confusion later on.

from tkinter import *
root = Tk()
root.title("Creater window")
def Img():
r = Toplevel()
r.title("My image")
canvas = Canvas(r, height=600, width=600)
canvas.pack()
my_image = PhotoImage(file='C:\\Python34\\Lib\idlelib\\Icons\\Baba.gif', master= root)
canvas.create_image(0, 0, anchor=NW, image=my_image)
r.mainloop()
btn = Button(root, text = "Click Here to see creator Image", command = Img)
btn.grid(row = 0, column = 0)
root.mainloop()

Related

Change background makes its labels disappear

I want to build an app where you can change the background image by clicking a button. First, to put a background to my frame, I created the image as a label and then sub-classed every other label to the background label. Now when you click the button "Change Background", it changes the background. However, all the labels disappear. Buttons only appear when you hover over them by the cursor. Labels never appear!
My questions are:
Why does this happen?
How to fix it?
Here is a simple code to reproduce the issue:
import tkinter as tk
from PIL import ImageTk, Image
class App():
def __init__(self, root):
self.root = root
self.controlFrame = tk.Frame(root, width=900, height=600)
self.controlFrame.pack_propagate(0) # Prevents resizing
self.controlFrame.pack()
img = Image.open('images/outside.jpg').resize((900, 600))
self.background_image = ImageTk.PhotoImage(img)
self.background_label = tk.Label(self.controlFrame, image=self.background_image)
self.background_label.configure(image = self.background_image)
self.background_label.pack(fill="both", expand="yes")
self.changeButton = tk.Button(self.background_label, text="Change Background",
command = self.changeBK)
self.changeButton.place(x=400, y=300)
self.someButton = tk.Button(self.background_label, text="Some Button")
self.someButton.place(x=400, y=100)
self.someOtherButton = tk.Button(self.background_label, text="Some Other Button")
self.someOtherButton.place(x=400, y=450)
self.userMessage = tk.Label(self.background_label, text="Label", height = 3 , width= 14, bg="white")
self.userMessage.place(x=400, y= 200)
def changeBK(self):
img = Image.open('images/muddyPath.jpg').resize((900, 600))
self.background_image = ImageTk.PhotoImage(img)
self.background_label.configure(image = self.background_image)
def main():
win = tk.Tk() # Create a window
win.title("Using Multiple Layouts") # Set window title
win.geometry("900x600") # Set window size
win.resizable(False, False) # Both x and y dimensions ...
# Create the GUI as a Frame
# and attach it to the window ...
myApp = App(win)
# Call the GUI mainloop ...
win.mainloop()
if __name__ == "__main__":
main()

Add an image on a 'price button' tkinter

A very simple question again. Once again, I have done my research on all websites but only one article kind of helps me.
Here is the article: How do I create a button in Python Tkinter to increase integer variable by 1 and display that variable?
And this is the code I am interested in (from the article above):
import tkinter
import sys
root = tkinter.Tk()
root.geometry("200x200")
root.title("His Button Increaser")
counter = tkinter.IntVar()
def onClick(event=None):
counter.set(counter.get() + 1)
tkinter.Label(root, textvariable=counter).pack()
tkinter.Button(root, text="Increase", command=onClick, fg="dark green", bg =
"white").pack()
root.mainloop()
Basically, I want to add an image to the button and remove the text on that button, so the user sees a picture, and when they click on the button, it displays the price at the top.
The part of my code I want to implement is:
PhotoImage(file = "imageofcar".png")
Thanks :)
To display an image on the button, you just have to pass the associated PhotoImage object to the Button through the parameter named image. Here is the solution:
import tkinter
root = tkinter.Tk()
root.geometry("200x200")
root.title("His Button Increaser")
counter = tkinter.IntVar()
def onClick(event=None):
counter.set(counter.get() + 1)
tkinter.Label(root, textvariable=counter).pack()
photo = tkinter.PhotoImage(file='imageofcar.png')
tkinter.Button(root, image=photo, command=onClick, fg="dark green", bg = "white").pack()
root.mainloop()
You can do this as following: First you create a PhotoImage object in which you pass the image you want to load as parameter, then you configure your button to accept this image at the specified size and finally you pack the button with pack():
from tkinter import *
import sys
root = Tk()
root.geometry("200x200")
root.title("His Button Increaser")
counter = IntVar()
def onClick(event=None):
counter.set(counter.get() + 1)
label = Label(root, textvariable=counter).pack()
button = Button(root, text="Increase", command=onClick, fg="dark green", bg = "white")
photo = PhotoImage(file = "imageofcar.png")
button.config(image=photo,width="100",height="100")
button.pack()
root.mainloop()
You can add an image to a button like this:
image = Image.open("imageofcar.jpg")
photo = ImageTk.PhotoImage(image)
b.config(image=photo)
where b is a reference to the button object.
It's usually a bad idea to create a Tk object and "pack" it in one line, because the pack function returns None.
These changes added to your code results in this:
import tkinter
import sys
from PIL import Image, ImageTk
root = tkinter.Tk()
root.geometry("200x200")
root.title("His Button Increaser")
counter = tkinter.IntVar()
def onClick(event=None):
counter.set(counter.get() + 1)
tkinter.Label(root, textvariable=counter).pack()
b = tkinter.Button(root, text="Increase", command=onClick, fg="dark green", bg =
"white")
b.pack()
image = Image.open("imageofcar.jpg")
photo = ImageTk.PhotoImage(image)
b.config(image=photo)
root.mainloop()

Python 3.5: Print Canvas Text

Could anyone share with me how to print the text of the text widget added to a Canvas object? In the code below, I want the system return the value of "hello" when mouse on the text, however, it turns out giving me "1". Don't know why. Could anyone help me?
Many many thanks!!!
import tkinter
from tkinter import *
def show_text(event):
print (canvas.text)
master = tkinter.Tk()
canvas = tkinter.Canvas(master, width = 200, height = 100)
canvas.pack()
canvas.bind('<Enter>',show_text)
canvas.text = canvas.create_text(20, 30, text="hello")
mainloop()
According to the canvas docs:
You can display one or more lines of text on a canvas C by creating a
text object:
id = C.create_text(x, y, option, ...)
This returns the object ID of the text object on canvas C.
Now, you gotta modify the code something like this:
import tkinter
from tkinter import *
def show_text(event):
print (canvas.itemcget(obj_id, 'text'))
master = tkinter.Tk()
canvas = tkinter.Canvas(master, width = 200, height = 100)
canvas.pack()
canvas.bind('<Enter>',show_text)
obj_id = canvas.create_text(20, 30, text="hello")
mainloop()
Follow up (see the documentation for Label.config:
import tkinter
from tkinter import *
from tkinter import ttk
def show_text(event):
print (canvas.itemcget(canvas.text, 'text'))
#The command of writing text 'hello' in sch_Label to replace the text 'the info shows here'
sch_Label.config(text = 'hello!')
master = tkinter.Tk()
canvas = tkinter.Canvas(master, width = 200, height = 100)
canvas.pack()
canvas.bind('<Enter>',show_text)
canvas.text = canvas.create_text(20, 30, text="hello")
pad1 = ttk.Notebook(master)
pad1.pack(side=RIGHT, expand=1, fill="both")
tab1 = Frame(pad1)
pad1.add(tab1, text = "Schedule")
pad1.pack(side=RIGHT)
sch_Label = ttk.Label(tab1, text='The info shows here')
sch_Label.pack(side="top", anchor="w")
mainloop()

tkinter image button not working inside a function [duplicate]

I am trying to place two image buttons on my image background in a certain position, but my buttons are not appearing. I think their images are behind the background.
I tried to use place and pack, both did not work. What could be the problem?
from tkinter import*
import tkinter as tk
import settings
class Application(Frame):
def __init__ (self, master):
Frame.__init__(self,master)
self.grid()
self.create_widgets()
def create_widgets(self):
button1 = PhotoImage(file ="button1.gif")
button2 = PhotoImage(file ="button2.gif")
settings_button = Button(self, image = button1,
command = self.mult_command, width = 15)
settings_button.place(x=1, y=1)
rules_button = Button(self, image = button2,
command = self.the_rules, width = 15)
rules_button.place(x=50, y=50)
def main_code():
window = Tk()
window.title("The Bouncer")
bg_image = PhotoImage(file ="pic.gif")
x = Label (image = bg_image)
x.image = bg_image
x.place(x = 0, y = 0, relwidth=1, relheight=1)
window.geometry("600x300")
app = Application(window)
window.mainloop()
main_code()
thanks
It is likely that your image is being garbage collected before it is displayed. This is a common Tkinter gotcha. Try changing the lines:
button1 = PhotoImage(file ="button1.gif")
button2 = PhotoImage(file ="button2.gif")
to
self.button1 = PhotoImage(file ="button1.gif")
self.button2 = PhotoImage(file ="button2.gif")
and use
settings_button = Button(self, image = self.button1, command = self.mult_command, width = 15)
etc.
This should keep a reference to your image, stopping it from getting garbage collected.
In addition to keeping a reference to the image, you have a problem with this line:
self.grid()
in the __init__ method of Application. It's gridding the Frame into the window, but since nothing is ever packed or gridded into the frame, it doesn't ever expand past a little, tiny frame, so you just don't see the Buttons inside it. A simple fix here would be the pack method, with arguments to fill the window and expand when needed:
self.pack(fill=BOTH, expand=1)

Why my image buttons are not appearing?

I am trying to place two image buttons on my image background in a certain position, but my buttons are not appearing. I think their images are behind the background.
I tried to use place and pack, both did not work. What could be the problem?
from tkinter import*
import tkinter as tk
import settings
class Application(Frame):
def __init__ (self, master):
Frame.__init__(self,master)
self.grid()
self.create_widgets()
def create_widgets(self):
button1 = PhotoImage(file ="button1.gif")
button2 = PhotoImage(file ="button2.gif")
settings_button = Button(self, image = button1,
command = self.mult_command, width = 15)
settings_button.place(x=1, y=1)
rules_button = Button(self, image = button2,
command = self.the_rules, width = 15)
rules_button.place(x=50, y=50)
def main_code():
window = Tk()
window.title("The Bouncer")
bg_image = PhotoImage(file ="pic.gif")
x = Label (image = bg_image)
x.image = bg_image
x.place(x = 0, y = 0, relwidth=1, relheight=1)
window.geometry("600x300")
app = Application(window)
window.mainloop()
main_code()
thanks
It is likely that your image is being garbage collected before it is displayed. This is a common Tkinter gotcha. Try changing the lines:
button1 = PhotoImage(file ="button1.gif")
button2 = PhotoImage(file ="button2.gif")
to
self.button1 = PhotoImage(file ="button1.gif")
self.button2 = PhotoImage(file ="button2.gif")
and use
settings_button = Button(self, image = self.button1, command = self.mult_command, width = 15)
etc.
This should keep a reference to your image, stopping it from getting garbage collected.
In addition to keeping a reference to the image, you have a problem with this line:
self.grid()
in the __init__ method of Application. It's gridding the Frame into the window, but since nothing is ever packed or gridded into the frame, it doesn't ever expand past a little, tiny frame, so you just don't see the Buttons inside it. A simple fix here would be the pack method, with arguments to fill the window and expand when needed:
self.pack(fill=BOTH, expand=1)

Categories