I am trying to create a function for multiple buttons that allows the user to click on a specific button and change the associated image. For now I'm trying to change the image of a single button, but the image doesn't seem to be loaded or recognized for some reason. Any ideas?
import tkinter as tk
from tkinter import simpledialog,filedialog,colorchooser,messagebox,Frame,Button
from PIL import ImageTk, Image
def img_mod():
global btn
ret = filedialog.askopenfilename()
loadn = Image.open(ret)
root.render2 = ImageTk.PhotoImage(loadn)
btn['image'] = loadn
root = tk.Tk()
load1 = Image.open("example.jpg")
root.render1 = ImageTk.PhotoImage(load1)
btn = tk.Button(root, text="My Button", image = root.render1)
btn['command'] = img_mod
btn.pack(fill='both', expand=True)
root.mainloop()
You can run this Python code if you save it with an image titled "example.jpg" in the same folder.
Related
I am using tkinter with python to click on an image.
Currently, after getting 1 image, I click on 1 image.
In the future I want to click an image for multiple images,
How can I dynamically add/remove reference images/wait seconds?
If there is a better way, I would appreciate it if you could tell me.
What you want to achieve
I am clicking the image with the script below.
I want to click an image for multiple images.
Adding a + button will add (2) dynamically.
-When the button is deleted, (2) is dynamically deleted and restored.
(1) Acquire image > Save
(2) Select the image saved in the folder
(Waiting seconds (until the image is clicked))
(3) Click image
(Multiple images with all selected and waiting seconds are executed.)
code
import tkinter as tk
from PIL import Image, ImageTk
import pyautogui
import time
import subprocess
import os
from tkinter import filedialog
import re
#Start SnippingTool, run when button is clicked
def image(event):
p = subprocess.Popen([r"C:\Windows\System32\SnippingTool.exe"])
selected_file = ""
# File reference, run when button is clicked
def file_select():
global selected_file
idir = 'C:\\python_test' #initial folder
filetype = [("all","*"),("text","*.txt"), ("music","*.mp3")] #Extension selection
file_path = tk.filedialog.askopenfilename(filetypes = filetype, initialdir = idir)
selected_file = file_path
input_box.insert(tk.END, file_path) # Display result
print(selected_file)
# wait seconds, run when button is clicked
def click_image():
global selected_file
# Substitute selected_file from the file reference function to get the coordinates of this PC icon
position=pyautogui.locateOnScreen(selected_file, confidence=0.9)
#position=pyautogui.locateOnScreen("C://Users///image//excel.PNG", confidence=0.9)
#Click the #maxwindowPC icon
pyautogui. doubleClick(position)
# Image click, run when button is clicked
def click_image():
global selected_file
# Substitute selected_file from the file reference function to get the coordinates of this PC icon
position=pyautogui.locateOnScreen(selected_file, confidence=0.9)
#position=pyautogui.locateOnScreen("C://Users///image//excel.PNG", confidence=0.9)
#Click the #maxwindowPC icon
try:
time.sleep(int(txt.get()))
except ValueError:
pass
pyautogui. doubleClick(position)
# create screen
window = tk.Tk()
window. geometry("300x300")
window.title("click image")
#Create image acquisition button
btn1 = tk.Button(window, text="① Get image")
# button display
btn1.place(x=15, y=15, width=150, height=40)
# bind a function to the button
btn1.bind("<Button-1>", image)
#Create an input field
input_box = tk.Entry(width=40)
input_box.place(x=10, y=100)
#Create result labels
input_label = tk.Label(text="② Image file selection")
input_label.place(x=10, y=70)
#Creating a browse button
button = tk.Button(text="reference", command=file_select)
button.place(x=10, y=130)
#Create result labels
input_label = tk.Label(text='waiting seconds')
input_label.place(x=10, y=160)
# Text box
txt = tk.Entry(width=15)
txt.place(x=15, y=180)
#Create an image click button
button = tk.Button(text="③Click image", command=click_image)
button.place(x=15, y=205, width=150, height=40)
# Screen display (resident)
window.mainloop()
I want to open images in Python by selecting them in a dialog box, how can I do that? I tried tkinter and easygui but when I use them the program freezes and never loads. Any suggestions?
As mentioned in the comments, you should provide a minimal reproducible example. Since you are a new member, I am giving you this example, which can be found here. https://www.geeksforgeeks.org/loading-images-in-tkinter-using-pil/
from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
def open_img():
# Select the Imagename from a folder
x = openfilename()
# opens the image
img = Image.open(x)
# resize the image and apply a high-quality down sampling filter
img = img.resize((250, 250), Image.ANTIALIAS)
# PhotoImage class is used to add image to widgets, icons etc
img = ImageTk.PhotoImage(img)
# create a label
panel = Label(root, image=img)
# set the image as img
panel.image = img
panel.grid(row=2)
def openfilename():
# open file dialog box to select image
# The dialogue box has a title "Open"
filename = filedialog.askopenfilename(title='"pen')
return filename
# Create a window
root = Tk()
# Set Title as Image Loader
root.title("Image Loader")
# Set the resolution of window
root.geometry("550x300+300+150")
# Allow Window to be resizable
root.resizable(width=True, height=True)
# Create a button and place it into the window using grid layout
btn = Button(root, text='open image', command=open_img).grid(row=1, columnspan=4)
root.mainloop()
I made a tkinter app for displaying images, and I was wondering if there's a way to make an image open by default with this app
At the moment if I try that, I get an error for some non declared icon file (this is the icon that appears near the name of the app at the top)
There's no real goal behin this Gui, I'm just experimenting and learning.
Thanks
Try this:
from PIL import Image, ImageTk
import tkinter as tk
from tkinter import filedialog
my_img = []
def FileImport():
file = filedialog.askopenfilename()
my_img.clear()
my_img.append(ImageTk.PhotoImage(Image.open(file)))
label1.config(image=my_img[0])
root= tk.Tk()
root.title('Main')
root.geometry('400x400')
label = tk.Label(root, text = "Browse", fg="purple")
label.pack()
button = tk.Button(root, text='See Image',fg="blue", command=FileImport)
button.pack()
my_img.append(ImageTk.PhotoImage(Image.open(your_first_image)))
label1 = tk.Label(root, image = my_img[0])
label1.pack(pady= 50)
root.mainloop()
When you run this:
After you tap to see different image from computer:
Hope It helps!
I've been trying to build a tkinter window that has some Check buttons, an image, and a button. I use the Spyder IDE and the code works just fine when I open Spyder and run it for the first time. But when I try to execute again, the image doesn't appear, and also apparently the window does not get destroyed by the button I've created. Is there something wrong with my code?
Here is my code:
import tkinter as tk # GUI configuration
from PIL import ImageTk, Image
# Window to select the analysis actions
config_window = tk.Tk()
config = { # Dictionary with variables that control what the algorithm will do
"EDIT_FILES": tk.BooleanVar(),
"RMS_ANALYSE": tk.BooleanVar(),
"WATERFALL_FFT": tk.BooleanVar()
}
config_window.title('Analysis settings')
label = tk.Label(config_window, text='Please check the boxes corresponding to the operations you would like to do',\
background='red')
label.grid(row=0, sticky='n')
tk.Checkbutton(config_window, text='Edit the files created from the sensor measurements', \
variable=config["EDIT_FILES"]).grid(row=1, sticky='w')
tk.Checkbutton(config_window, text='RMS analysis', \
variable=config["RMS_ANALYSE"]).grid(row=2, sticky='w')
tk.Checkbutton(config_window, text='FFT analysis', \
variable=config["WATERFALL_FFT"]).grid(row=3, sticky='w')
image = Image.open("logo.png").resize((220,80), Image.ANTIALIAS)
logo = ImageTk.PhotoImage(image, size=10)
im_label = tk.Label(image=logo)
im_label.image = logo
im_label.grid(row=4, sticky='w')
tk.Button(config_window, text='Ok', width=10, command=config_window.destroy).grid(row=4, sticky='e')
config_window.mainloop()
I made a GUI with few buttons and I want to change the gray background to an image.
my code looks like this:
from tkinter import *
from urlread import givenumbers # my function
""" Setting The Main GUI """
GUI = Tk()
GUI.title('Check GUI')
GUI.iconbitmap('test.ico')
GUI.geometry("400x400")
background_image=PhotoImage('pic.jpg')
background_label = Label(GUI, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
""" Reading Images For Buttons """
A_Im = PhotoImage(file='A.gif')
""" Creating Buttons """
# A Button
A_Button = Button(GUI, image=A_Im, command=givenumbers)
A_Button.grid(column=0, row=1)
GUI.mainloop()
The code runs without error but the background is still gray without any effect.
The problem is in the line background_image=PhotoImage('pic.jpg'). The PhotoImage class only supports GIF-files, which means that it cannot read the file you're specifying. You should try something like this:
#Python 2.7
import Tkinter as tk
from PIL import Image, ImageTk
window = tk.Tk()
image = Image.open('image.jpg')
photo_image = ImageTk.PhotoImage(image)
label = tk.Label(window, image = photo_image)
label.pack()
# Python 3
import tkinter as tk
from PIL import Image, ImageTk
window = tk.Tk()
image = Image.open('image.jpg')
photo_image = ImageTk.PhotoImage(image)
label = tk.Label(window, image = photo_image)
label.pack()
The Image class from the PIL module supports a variety of formats, among which jpeg and png. You can install the PIL module by running pip install pillow in a command prompt or terminal.
If you want to put the widgets on top of the Label, you could indeed using grid to get them on top of each other, but using a Canvas would probably be easier. You can find more about the Canvas widget here.
This can be done without pil also:
from tkinter import *
import tkinter as ttk
""" Setting The Main GUI """
GUI = Tk()
F1=Frame(GUI)
F1=Frame(GUI,width=400,height=450)
F1.place(height=7000, width=4000, x=100, y=100)
F1.config()
F1.grid(columnspan=10,rowspan=10)
F1.grid_rowconfigure(0,weight=1)
F1.grid_columnconfigure(0,weight=1)
photo=PhotoImage(file="C:\\Users\\HOME\\Desktop\\Eshita\\12th\\computer
\\python\\GUI\\math3.gif")
label = Label(GUI,image = photo)
label.image = photo # keep a reference!
label.grid(row=0,column=0,columnspan=20,rowspan=20)
b=ttk.Button(GUI,text="Start")
b.grid(row=8,column=8)
GUI.mainloop()