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()
Related
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()
Try to capture the image of a widget in tkinter window by following code, but just get the screen area under tkinter window.
import ctypes
import platform
from time import sleep
import tkinter as tk
from PIL import ImageGrab
if platform.system() == "Windows" and platform.release() == "10":
ctypes.windll.shcore.SetProcessDpiAwareness(1)
root = tk.Tk()
root.geometry("+0+0")
var = tk.StringVar()
var.set("Hello World")
entry = tk.Entry(root, width=40, bg='green', takefocus=False, textvariable=var)
entry.pack()
root.update()
# sleep(1)
x, y = entry.winfo_rootx(), entry.winfo_rooty()
width, height = entry.winfo_width(), entry.winfo_height()
im = ImageGrab.grab(bbox=(x, y, x+width, y+height)) # Grab image on screen
im.show()
root.mainloop()
It will be OK if line # sleep(1) replaced by sleep(1). Had been tried method update or update_idletasks, all got same results.
Is there any method to finalize tkinter window immediately ? So I don't need to sleep one second each time to grap image of a widget. Or I get wrong way to go it, any suggestion is welcome.
It is obvious right? It needs to take some time to show the window but the screenshot is captured quite quickly. What do I suggest? Put it inside a function and take advantage of the after method here.
def screenshot():
im = ImageGrab.grab(bbox=(x, y, x+width, y+height)) # Grab image on screen
im.show()
root.after(1000,screenshot) # Depending on the time required to take show the window
So, i was trying to make a music player with python and tkinter and I had to set images for the buttons, but when I set an image for the button, the button does not appear on the output screen
Code:
from tkinter import *
import pygame
win = Tk()
win.title("Music player")
win.geometry("500x300")
# Images for buttons
back_png = PhotoImage("C:/1 Files and Folders/SHARAN/Python/SVE atom/Images/back.png")
back_button = Button(win, image=back_png, borderwidth=0).place(x=100, y=20)
win.mainloop()
tkinter requires a keyword for most arguments. Here you are missing the file= keyword.
back_png = PhotoImage(file="C:/1 Files and Folders/SHARAN/Python/SVE atom/Images/back.png")
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.
The script below does is if I copy a link like this: http://urlshortener.io/s/1234rIHs/?s=https%3A%2F%2Fexample.com%2Fsome_content%2F, it will change to
example.com/some_content/ if I clicked the button.
Is there a way that when I run this script then it will listen in the background for a "copy" action, and then if I copy some text in my browser, it will automatically slice the text I just copied and I won't need to click the button?
Right now, I still have to click the button in order for the slicing to happen.
from tkinter import *
from urllib import parse
from tkinter import Tk
root = Tk()
root.title("Slicer")
root.geometry('304x70')
lbl = Label(root, text="Link")
lbl.pack()
def clicked():
clip = root.clipboard_get()
clip = parse.unquote(clip)[45:]
root.clipboard_clear()
root.clipboard_append(clip)
lbl.configure(text= clip)
btn = Button(root, text="Slice", command=clicked, height = 3, width = 40)
btn.pack()
root.mainloop()
You can use pyperclip. Run an infinite loop, keep detecting for urls in the loop, modify when found.
import pyperclip, time
# Modify is_url and modify_url, according to your need
def is_url(s):
return True
def modify_url(url_string):
return "Hello World"
while True:
on_clip = pyperclip.paste()
if is_url(on_clip):
pyperclip.copy(modify_url(on_clip))
time.sleep(0.1)