Create image in button - python

How do I create an image in button. Instead of having text saying "Draw" I want it to be a picture of a brush.
Code:
self.draw_button = Button(self.root, text='Draw', command=self.use_draw)
self.draw_button.grid(row=0, column=2)

Create an image with tkinter's PhotoImage then set it inside Button.
from tkinter import *
root = Tk()
img = PhotoImage(file='paint_brush.png')
draw_button = Button(root, image=img)
draw_button.grid(row=0, column=0)
root.mainloop()

Related

When I open new window with button click, also another mini window pops up

I want to open new window with button click and close the old one. I tried to do that with this code, but when I click button it's also open another mini window with title 'tk'. How can I prevent that?
from tkinter import *
from PIL import Image, ImageTk
def openOperationsGui():
window.destroy()
operationsWindow = Toplevel()
operationsWindow.title("Operations")
operationsWindow.geometry("1366x768")
window = Tk()
logo = Image.open("resources\logo.png")
logoImg = ImageTk.PhotoImage(logo)
logoLbl = Label(image=logoImg)
logoLbl.place(x=450, y=120, height=500, width=500)
conn = Button(window, text="Connect", fg='blue', command=openOperationsGui)
conn.place(x=450, y=533, height=87, width=490)
passw = Entry(window, text="", bd=5)
passw.place(x=620, y=480, height=50, width=150)
window.title('Title')
window.geometry("1366x768")
window.mainloop()

How can I manage to put a button image into an image background Tkinter

Good day everyone, can I ask how can I manage to put this button inside an image background
code:
from tkinter import *
from PIL import ImageTk, Image
root = Tk()
root.title("Japanese Retro Hub")
root.geometry('2200x1000')
#Image
bg = Image.open("RetroHub_BG_Main.png")
resized = bg.resize((2200,1000), Image.ANTIALIAS)
bg = ImageTk.PhotoImage(resized)
bglabel = Label(root, image=bg)
bglabel.pack(pady=20)
#text for my_command and Start exit button
text = Label(root, text= "Hello world")
text.pack(pady=30)
def my_command():
text.config(text="You have clicked Me...")
def start_exit_button():
click_btn = PhotoImage(file='start_button.png')
img_label= Label(image=click_btn)
button = Button(root, image=click_btn,command=my_command,borderwidth=0)
button.pack(padx=50, pady=20)
root.mainloop()
start_exit_button()
root.mainloop()
This is the image example that I am trying to portray
https://drive.google.com/file/d/1VzbhNazEnfOCk0_QZOD_nWR5jsb-a8GB/view?usp=sharing

Color button background permanently when clicked, and without pressure effect?

I built a button image (first image), but I manually added the neighboring text as plain text. I would like to make sure that clicking on the button (image or text) the background color of the button becomes permanent (second image).
I don't like the effect of pressing the button, I just want the background color of the button. Can I modify the button I created by merging image + text into a single selection? Or do you have to create the button in another way? If so, can you show me how? I found some buttons on the web, but they're not how I want them: I don't like that it looks like a button (I don't want the rectangular outline, I don't want the effect of pressing). How can I do?
Code:
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import tkinter as tk
from tkinter import ttk
from PIL import ImageTk, Image
root = Tk()
root.title("xxxx")
root.geometry("1920x1080+0+0")
root.config(bg="#f0f0f0")
root.state("normal")
topbar=Frame(root, width=2200, height=43, background="#e10a0a")
topbar.place(x=0, y=0)
leftbar=Frame(root, width=250, height=1400, background="white")
leftbar.place(x=1, y=44)
button1= tk.PhotoImage(file="/image.png")
btn1 = tk.Button(root, image=button1, borderwidth=0, highlightthickness=0, bg="white", text="sdsdsd", foreground='green')
btn1.place(x=2, y=43)
text1 = Label(root, text="aaaaa", bg="white", foreground='black', font='Verdana 12')
text1.place(x=70, y=58)
button2= tk.PhotoImage(file="/image.png")
btn2 = tk.Button(root, image=button2, borderwidth=0, highlightthickness=0, bg="white", text="sdsdsd", foreground='green')
btn2.place(x=2, y=100)
text2 = Label(root, text="bbbbbb", bg="white", foreground='black', font='Verdana 12')
text2.place(x=70, y=120)
UPDATE 1
After using compound, I get this. I don't know if it's the best solution. I get closer, but I still don't have what I need. I would like to stretch the selection color to the end of the white rectangle, then I would like to permanently color the background of the button
UPDATE 2
By applying width = 224, I fix the button background color length problem, but the button is centered. Now there is space to his left, before it wasn't there. I would like it in the starting position on the left
You can combine image and text in a button by setting compound option.
Also suggest to use pack() instead of place() for laying out the frames and buttons for your case.
And I think the parent of those buttons should be leftbar instead of root.
Below is the modified code:
from tkinter import messagebox
import tkinter as tk
from tkinter import ttk
from PIL import ImageTk, Image
root = tk.Tk()
root.title("xxxx")
root.geometry("1920x1080+0+0")
root.config(bg="#f0f0f0")
root.state("normal")
topbar = tk.Frame(root, background="#e10a0a", height=43)
topbar.pack(fill='x') # use pack() instead of place()
leftbar = tk.Frame(root, width=250, background="white")
leftbar.pack(side='left', fill='y') # use pack() instead of place()
leftbar.pack_propagate(0) # disable size auto-adjustment
def clicked(btn):
for w in leftbar.winfo_children():
w['bg'] = 'white' if w is not btn else 'yellow'
button1 = tk.PhotoImage(file="/image.png")
btn1 = tk.Button(leftbar, image=button1, borderwidth=0, highlightthickness=0,
bg="white", text="aaaaa", foreground='green', compound='left', anchor='w')
btn1.pack(fill='x') # use pack() instead of place()
btn1['command'] = lambda: clicked(btn1)
button2 = tk.PhotoImage(file="/image.png")
btn2 = tk.Button(leftbar, image=button2, borderwidth=0, highlightthickness=0,
bg="white", text="bbbbb", foreground='green', compound='left', anchor='w')
btn2.pack(fill='x') # use pack() instead of place()
btn2['command'] = lambda: clicked(btn2)
root.mainloop()
The output:

How to use user input to display image?

How do I use user input to retrieve an image, and display it on the screen? I have the user input field in Tkinter, and I do not know how to get that to go to my folder, and get the image to show up on the same screen.
EDIT: I was able to get the path to show on the screen, but now I don't know how to get the actual image to show up from that path inside the frame... I do not know how to link this path to have the program display the image, i.e. myimage1 from my folder.
from tkinter import *
from PIL import ImageTk,Image
from tkinter import ttk
from tkinter import filedialog
root = Tk()
root.title("Images")
root.iconbitmap(r'C:\Users\hadhikari\example\Takumi_Logo.ico')
button_quit = Button(root, text= "Exit Program", command=root.quit)
button_quit.pack()
e= Entry(root, width=50, bg="light blue", borderwidth=3)
e.pack()
e.insert(0," ")
def myClick():
link = "r'C:\\Users\\hadhikari\\example\\" + e.get()
myLabel1 = Label(root, text=link)
myLabel1.pack()
myButton = Button(root, text="Scan Part Number", command=myClick,
bg="pink", fg="white")
myButton.pack()
#my_img = ImageTk.PhotoImage(Image.open('link'))
#my_Label = Label(image=my_img)
#my_Label.pack()
#def getText():
# inputtedtext = entrybox.get()
#entrybox = Entry(root)
#entrybox.pack()
#btn = Button(root, text="Submit", command=getText)
#btn.pack()
frame = LabelFrame(root, padx=100, pady=100)
frame.pack(padx=50, pady=50)
root.mainloop()
As suggested in the comments, maybe using Tkinter's askopenfilename dialog might be a better choice than hardcoding the filepath, and letting the user input the filename.
But, first of all, let's fix the code following your intentions. Most of the part on how to properly set up a Tkinter Label, and dynamically place images in that, can be easily found, for example in this Q&A. Basically, you want to put the "update routine" inside your myClick method:
from tkinter import *
from PIL import Image, ImageTk
# How to properly set up Tkinter label with dynamically changeable
# ImageTk.PhotoImage: https://stackoverflow.com/a/3482156/11089932
root = Tk()
button_quit = Button(root, text='Exit Program', command=root.quit)
button_quit.pack()
e = Entry(root, width=50, bg='light blue', borderwidth=3)
e.pack()
e.insert(0, '')
my_label = Label()
my_label.pack()
def myClick():
link = r'your/path/goes/here' + e.get()
my_img = ImageTk.PhotoImage(Image.open(link))
my_label.configure(image=my_img)
my_label.image = my_img
myButton = Button(root, text='Scan Part Number', command=myClick,
bg='pink', fg='white')
myButton.pack()
root.mainloop()
Program at startup:
Opening the first image:
Opening another image:
Now, regarding the askopenfilename dialog, we get rid of the Entry widget, and simply open the dialog inside the myClick method:
from tkinter import *
from tkinter.filedialog import askopenfilename
from PIL import Image, ImageTk
# How to properly set up Tkinter label with dynamically changeable
# ImageTk.PhotoImage: https://stackoverflow.com/a/3482156/11089932
root = Tk()
button_quit = Button(root, text='Exit Program', command=root.quit)
button_quit.pack()
my_label = Label()
my_label.pack()
def myClick():
link = askopenfilename()
my_img = ImageTk.PhotoImage(Image.open(link))
my_label.configure(image=my_img)
my_label.image = my_img
myButton = Button(root, text='Scan Part Number', command=myClick,
bg='pink', fg='white')
myButton.pack()
root.mainloop()
Program at startup:
Opening the first image (dialog):
Opening the first image (display):
----------------------------------------
System information
----------------------------------------
Platform: Windows-10-10.0.19041-SP0
Python: 3.9.1
PyCharm: 2021.1.3
Pillow: 8.3.1
----------------------------------------

Displaying image on Tkinter button click

I'm building an app that's supposed to display various images from a local folder depending on which button is clicked in the app.
So far, I have started out with an example I've found and try to modify it, but I can't figure out how to summon a .jpg or .png via a button click in the first place. Here's my very basic code so far:
import tkinter as tk
def write_slogan():
print("Tkinter is easy to use!")
root = tk.Tk()
frame = tk.Frame(root)
frame.pack()
button = tk.Button(frame,
text="QUIT",
fg="red",
command=quit)
button.pack(side=tk.LEFT)
slogan = tk.Button(frame,
text="Hello",
command=write_slogan)
slogan.pack(side=tk.LEFT)
root.mainloop()
Essentially, instead of writing the slogan in the console, I would like the button click to trigger an image being displayed. How would I go about achieving that?
I have amended your code so when you click your button the image "test.png" will display on a label.
Here is the code for testing, in my case "test.png" was in the same directory as my Python script.
import tkinter as tk
render = None
def write_slogan():
# get image and display
image = tk.PhotoImage(file = "test.png")
imageLabel.configure(image = image)
imageLabel.image = image
root = tk.Tk()
frame = tk.Frame(root)
frame.pack()
button = tk.Button(frame,
text="QUIT",
fg="red",
command=quit)
button.pack(side=tk.LEFT)
slogan = tk.Button(frame,
text="Hello",
command=write_slogan)
slogan.pack(side=tk.LEFT)
imageLabel = tk.Label(frame)
imageLabel.pack(side=tk.LEFT)
root.mainloop()
Also, this thread was helpful.
You can pass the image filename to the function, so that different buttons show different images:
import tkinter as tk
from PIL import ImageTk
def show_image(imagefile):
image = ImageTk.PhotoImage(file=imagefile)
imagebox.config(image=image)
imagebox.image = image # save a reference of the image to avoid garbage collection
root = tk.Tk()
frame = tk.Frame(root)
frame.pack()
button = tk.Button(frame, text="QUIT", fg="red", command=quit)
button.pack(side=tk.LEFT)
slogan = tk.Button(frame, text="Hello", command=lambda: show_image("slogan.png"))
slogan.pack(side=tk.LEFT)
other = tk.Button(frame, text="World", command=lambda: show_image("other.jpg"))
other.pack(side=tk.LEFT)
# label to show the image
imagebox = tk.Label(root)
imagebox.pack()
root.mainloop()
Since tk.PhotoImage() does not support JPG image, external Pillow module is used instead.

Categories

Resources