Add an image on a 'price button' tkinter - python

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()

Related

how to bind button in tkinter

import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title("Tic Tac Toe")
root.geometry("505x500")
root.resizable(0,0)
Blank = tk.PhotoImage(file='Blank.png')
X = tk.PhotoImage(file='X.png')
O = tk.PhotoImage(file='O.png')
def configB(event):
print('hello')
btn1 = tk.Button(root,image=Blank)
btn1.place(x=0,y=0)
btn2 = ttk.Button(image=Blank)
btn2.place(x=165,y=0)
btn3 = ttk.Button(image=Blank)
btn3.place(x=330,y=0)
btn4 = ttk.Button(image=Blank)
btn4.place(x=0,y=165)
btn5 = ttk.Button(image=Blank)
btn5.place(x=165,y=165)
btn6 = ttk.Button(image=Blank)
btn6.place(x=330,y=165)
btn7 = ttk.Button(image=Blank)
btn7.place(x=0,y=330)
btn8 = ttk.Button(image=Blank)
btn8.place(x=165,y=330)
btn9 = ttk.Button(image=Blank)
btn9.place(x=330,y=330)
btn1.bind('<Return>',configB)
root.mainloop()
i want to bind btn1 and i want it to work when i press enter but nothing happens when i press enter as per my code it should print hello .
please help thanks in advance.
As #jasonharper said it will work only if button is focused
btn1.focus()
btn1.bind('<Return>', configB)
and if you click other button then it will not work again
so better bind to main winodw
root.bind('<Return>', configB)
Minimal working code
import tkinter as tk
# --- functions --- # PEP8: lower_case_names
def config_b(event):
print('hello')
# --- main ---
root = tk.Tk()
btn1 = tk.Button(root, text='1')
btn1.pack()
btn1 = tk.Button(root, text='2')
btn1.pack()
#btn1.focus()
#btn1.bind('<Return>', config_b)
root.bind('<Return>', config_b)
root.mainloop()
There is no quick answer to this question.
Buttons must be bound so as to duplicate (as close as possible) normal button behaviour.
This includes changing button relief and colors, then restoring button.
Finally it has to execute the button command.
The following example does this for two buttons.
'button' responds to Mouse 'Button-3'
'buttonX' responds to Key 'Return'
import tkinter as tk
def working():
print("Working...")
def actionPress(event):
event.widget.config(
relief = "sunken",
background = "red",
foreground = "yellow")
def actionRelease(event):
event.widget.config(
relief = "raised",
background = "SystemButtonFace",
foreground = "SystemButtonText")
# activate buttons' command on release
event.widget.invoke()
window = tk.Tk()
button = tk.Button(window, text = "press", command = working)
button.pack()
buttonX = tk.Button(window, text = "pressX", command = working)
buttonX.pack()
# bind returns unique ID
boundP = button.bind("<ButtonPress-3>", actionPress)
boundR = button.bind("<ButtonRelease-3>", actionRelease)
boundXP = buttonX.bind("<KeyPress-Return>", actionPress)
boundXR = buttonX.bind("<KeyRelease-Return>", actionRelease)
# This is how to unbind (if necessary)
# button.unbind(""<ButtonPress-3>", boundP)
# button.unbind(""<ButtonRelease-3>", boundR)
# buttonX.unbind(""<KeyPress-Return>", boundXP)
# buttonX.unbind(""<KeyRelease-Return>", boundXR)
window.mainloop()
You don't need parameter in configB method. Also don't need bind for button1. I also add command in button1 widget. Comment out in line 36 #btn1.bind('<Return>',configB)
def configB():
print('hello')
btn1 = tk.Button(root, command=configB)
Result:
Btw, I don't have png image.

How to call Turtle window from a GUI

I'm trying to open a Turtle window from a GUI to select a position on the image with a mouse click. The x and y coordinates are then returned as an input to the GUI.
Here is a minimal working example:
from tkinter import *
from tkinter import font as tkFont
import turtle
xclick = 0
yclick = 0
def callback3():
getcoordinates()
def getcoordinates():
screen = turtle.Screen()
screen.setup(400, 400)
screen.bgpic("stunden.gif")
screen.onscreenclick(modifyglobalvariables)
def modifyglobalvariables(rawx,rawy):
global xclick
global yclick
xclick = int(rawx//1)
yclick = int(rawy//1)
print(xclick)
print(yclick)
turtle.bye()
root = Tk()
helv30 = tkFont.Font(family='Helvetica', size=30)
button1 = Button(root, text = "1", width=3, font=helv30, borderwidth=0, command=callback3)
button1.grid(row=0, column=0, padx=5, pady=0)
root.mainloop()
Then the error image "pyimage2" doesn't exist shows up. I found out, that it has something to do with two instances of Tk, as there is the root and the turtle window and that I should solve it with Toplevel(). However, after hours of research and try and error I still could not come up with the right solution to make my code work. Any help is greatly appreciated.
Here's how to implement it directly in tkinter — so no turtle module required — as I suggested earlier in a (now-deleted) comment:
from tkinter import *
from tkinter import font as tkFont
CLOCK_IMAGE_PATH = 'clock.png'
xclick, yclick = 0, 0
def callback3():
window = Toplevel()
window.title("Stunden")
img = PhotoImage(file=CLOCK_IMAGE_PATH)
img_width, img_height = img.width(), img.height()
window.minsize(width=img_width, height=img_height)
canvas = Canvas(window, width=img_width, height=img_height)
canvas.pack()
canvas.image = img # Keep reference to avoid image being garbage collected.
canvas.create_image(0, 0, anchor='nw', image=img)
canvas.bind("<Button-1>", get_coordinates) # Set up event-handler callback.
def get_coordinates(event):
global xclick, yclick
xclick = int(event.x // 1)
yclick = int(event.y // 1)
print(f'xclick={xclick}, yclick={yclick}')
root = Tk()
helv30 = tkFont.Font(family='Helvetica', size=30)
button1 = Button(root, text="1", width=3, font=helv30, borderwidth=0, command=callback3)
button1.grid(row=0, column=0, padx=5, pady=0)
root.mainloop()

How can I update the photo within a button using radio buttons?

I'm currently trying to learn how to build GUIs with tkinter, and I've run into a problem with my test app.
I have a button that displays an image on it instead of text, and I also have a set of radio buttons that I want to control which image is shown on the regular button. Currently the radio buttons don't seem to be updating my photofilepath StringVar as the button always has the default photo, regardless of selected radio button. Here is my (Simplified) code:
root = Tk() # Set up
root.title("Test GUI")
gui.grid(column=0, row=0, sticky=(N, W, E, S))
photofilepath = StringVar() # Set default photo
photofilepath.set("C:/Users/Ben/Pictures/Default photo.png")
photo = PhotoImage(file=photofilepath.get())
CalcButton = ttk.Button(gui, image=photo)
CalcButton.grid(column=3, row=2, columnspan=1)
# Set button photo
Photo1Rbutton = ttk.Radiobutton(gui, text="Photo 1", variable=photofilepath,
value='C:/Users/Ben/Pictures/Photo 1.png')
Photo1Rbutton.grid(column=4, row=2, sticky=S)
Photo2Rbutton = ttk.Radiobutton(gui, text="Photo 2", variable=photofilepath,
value='C:/Users/Ben/Pictures/Photo 2.png')
Photo2Rbutton.grid(column=4, row=3)
root.mainloop()
Thanks in advance for any help.
You can use command= in Radiobutton to assign function which will load new image and put them in label.
Working example (you have to only set paths)
import tkinter as tk
from tkinter import ttk
# to easily change example
DEFAULT = "C:/Users/Ben/Pictures/Default photo.png"
PHOTO_1 = "C:/Users/Ben/Pictures/Photo 1.png"
PHOTO_2 = "C:/Users/Ben/Pictures/Photo 2.png"
def change_image():
print(photo_filepath.get())
photo = tk.PhotoImage(file=photo_filepath.get())
calc_button['image'] = photo
calc_button.image = photo # solution for garbage-collector problem. you have to assign PhotoImage object to global variable or class variable
# - or -
photo['file'] = photo_filepath.get()
calc_button['image'] = photo
root = tk.Tk() # Set up
root.title("Test GUI")
photo_filepath = tk.StringVar() # Set default photo
photo_filepath.set(DEFAULT)
photo = tk.PhotoImage(file=photo_filepath.get())
calc_button = ttk.Button(root, image=photo)
calc_button.grid(column=3, row=2, columnspan=1)
photo1_radiobutton = ttk.Radiobutton(root, text="Photo 1", variable=photo_filepath,
value=PHOTO_1, command=change_image)
photo1_radiobutton.grid(column=4, row=2, sticky=tk.S)
photo2_radiobutton = ttk.Radiobutton(root, text="Photo 2", variable=photo_filepath,
value=PHOTO_2, command=change_image)
photo2_radiobutton.grid(column=4, row=3)
root.mainloop()

Image not displaying in Tkinter Label widget

I'm trying to get an image to display in a Tkinter Label widget. This code works inside a class in PyCharm, but doesn't get past the 'tk.Label' line in the main app. I've consulted other answers here but haven't been able to figure out why the image isn't displaying in the main app.
logo_filepath = "/Users/xxx/MASTER/pymol/Master/cache/logos/tmpbhWv2Ts.gif"
self.img = tk.PhotoImage(file = logo_filepath)
self.logo = tk.Label(self, image=self.img)
self.logo.photo = self.img
self.logo.grid(row=0, column=3, rowspan=10, columnspan=4)
It's a very simple error. Just make sure that you aren't defining self.[Your Variable] outside of a class. Because self is only available in classes. Also, Here's my code:
import Tkinter as tk
root = tk.Tk()
logo_filepath = "Your File Path..."
img = tk.PhotoImage(file = logo_filepath)
logo = tk.Label(root, image=img)
logo.photo = img
logo.grid(row=0, column=3, rowspan=10, columnspan=4)
tk.mainloop()

Image in tkinter window by clicking on button

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()

Categories