The main problem with your code is that you create a new PhotoImage for each pixel! Instead, create the PhotoImage once and just add the pixels in the double-for-loop.

def box(event):
    yaxis(event)
    canvas.create_rectangle(x1, y1, x2, y2)

    picture = PhotoImage(width=(x2-x1), height=(y2-y1))
    for x in range(x1, x2):
        for y in range(y1, y2):
            r, g, b = photo.get(x, y)
            picture.put("#%02x%02x%02x" % (r, g, b), (x-x1, y-y1))
    picture.write('new_image.gif', format='gif')

Also, the line tuple(map(int, value.split(" "))) in your getRGB function is wrong, as value is already the tuple you want to create, not a string.1) As you can see, I just 'inlined' that part directly into the box function. Another problem was that you wrote the copied pixels to x and y, but you have to write them to x-x1 and y-y1 instead.

Update 1: 1) It seems like the return value of PhotoImage.get depends on the version of Python/Tkinter you are using. In some versions, it returns a tuple, like (41, 68, 151), and in others, a string, like u'41 68 151'.

Update 2: As pointed out by @Oblivion, you can in fact just use the from_coords parameter of PhotoImage.write to specify the region of the picture to be saved to file. With this, the box function can be simplified as

def box(event):
    yaxis(event)
    canvas.create_rectangle(x1, y1, x2, y2)
    photo.write('new_image.gif', format='gif', from_coords=[x1, y1, x2, y2])
Answer from tobias_k on Stack Overflow
🌐
Java Code Geeks
javacodegeeks.com › home › web development › python
Explore These 20 Cool Python Scripts for Fun and Productivity! - Java Code Geeks
February 23, 2025 - This script demonstrates basic data encryption and decryption using the Fernet library. Objective: Build a RESTful API using Flask for serving and consuming data. ... from flask import Flask, jsonify, request app = Flask(__name__) # Sample data books = [ {'id': 1, 'title': 'Python Crash Course', 'author': 'Eric Matthes'}, {'id': 2, 'title': 'Fluent Python', 'author': 'Luciano Ramalho'} ] # GET request to retrieve all books @app.route('/books', methods=['GET']) def get_books(): return jsonify({'books': books}) # POST request to add a new book @app.route('/books', methods=['POST']) def add_book(): new_book = request.get_json() books.append(new_book) return jsonify({'message': 'Book added successfully'}) if __name__ == '__main__': app.run(port=5000)
Top answer
1 of 2
2

The main problem with your code is that you create a new PhotoImage for each pixel! Instead, create the PhotoImage once and just add the pixels in the double-for-loop.

def box(event):
    yaxis(event)
    canvas.create_rectangle(x1, y1, x2, y2)

    picture = PhotoImage(width=(x2-x1), height=(y2-y1))
    for x in range(x1, x2):
        for y in range(y1, y2):
            r, g, b = photo.get(x, y)
            picture.put("#%02x%02x%02x" % (r, g, b), (x-x1, y-y1))
    picture.write('new_image.gif', format='gif')

Also, the line tuple(map(int, value.split(" "))) in your getRGB function is wrong, as value is already the tuple you want to create, not a string.1) As you can see, I just 'inlined' that part directly into the box function. Another problem was that you wrote the copied pixels to x and y, but you have to write them to x-x1 and y-y1 instead.

Update 1: 1) It seems like the return value of PhotoImage.get depends on the version of Python/Tkinter you are using. In some versions, it returns a tuple, like (41, 68, 151), and in others, a string, like u'41 68 151'.

Update 2: As pointed out by @Oblivion, you can in fact just use the from_coords parameter of PhotoImage.write to specify the region of the picture to be saved to file. With this, the box function can be simplified as

def box(event):
    yaxis(event)
    canvas.create_rectangle(x1, y1, x2, y2)
    photo.write('new_image.gif', format='gif', from_coords=[x1, y1, x2, y2])
2 of 2
0
import tkinter
from tkinter import *
import base64

root = Tk()

def action(canvas):
    canvas.bind("<Button-1>", xaxis)
    canvas.bind("<ButtonRelease-1>", yaxis)
    canvas.bind("<ButtonRelease-1>", box)

def xaxis(event):
    global x1, y1
    x1, y1 = (event.x - 1), (event.y - 1)
    print (x1, y1)

def yaxis(event):
    global x2, y2
    x2, y2 = (event.x + 1), (event.y + 1)
    print (x2, y2)

def box(event, photo):
    x1, y1 = (event.x - 1), (event.y - 1)
    x2, y2 = (event.x + 1), (event.y + 1)
    canvas.create_rectangle(x1, y1, x2, y2)
    new_photo = copy_photo(photo, x1, y1, x2, y2)
    new_photo.write('new_image.gif', format='gif')

def copy_photo(photo, x1, y1, x2, y2):
    new_photo = PhotoImage(width=photo.width(), height=photo.height())
    for x in range(photo.width()):
        for y in range(photo.height()):
            if x1 <= x < x2 and y1 <= y < y2:
                r,g,b = getRGB(photo, x, y)
                new_photo.put("#%02x%02x%02x" % (r,g,b), (x,y))
            else:
                new_photo.put(photo.get(x, y), (x,y))
    return new_photo

def getRGB(photo, x, y):
    value = photo.get(x, y)
    return tuple(map(int, value.split(" ")))

canvas = Canvas(width=500, height=250)
canvas.pack(expand=YES, fill=BOTH)
photo = PhotoImage(file="picture.gif")
canvas.create_image(0, 0, image=photo, anchor=NW)
canvas.config(cursor='cross')
action(canvas)

enter code here

canvas.mainloop()
Discussions

Share the code you're most proud of!
It's not my most favourite but it can be handy now and again from __future__ import print_function import time class timer(object): def __init__(self, func=print): self.func = func def __enter__(self): self.time = time.time() def __exit__(self, type, value, traceback): total_time = time.time() - self.time self.func(total_time) If you want to know how long some code takes to run just use with timer(): # do something and it will print out how long it took to finish whatever it was that you wanted to do. It can also take in a function as an argument time_taken = [] for i in range(1000000): with timer(time_taken.append) # do something this will add the amount of time taken each time to a list and the average time can be obtained in a similar fashion to timeit. EDIT: Added time and print_function imports as suggested below. Also this should really only be used for rough timings or where what is being timed takes milliseconds and longer to compute to account for the extra overheads involved More on reddit.com
🌐 r/Python
264
181
March 20, 2014
Cool scripts that help you with your daily life
Me and a buddy are working on a program to automatically login to our online games and collect daily rewards. More on reddit.com
🌐 r/Python
38
39
August 19, 2022
Copy and Paste Files - Command
Good night people, I have a problem, I used the following code to copy and paste files from one folder to another import os import time import shutil origem = r"C:\Program Files\Corel\CorelDRAW Graphics Suite 2022\Programs64\Pasta2" destino = r"C:\Program Files\Corel\CorelDRAW Graphics Suite ... More on discuss.python.org
🌐 discuss.python.org
0
0
June 24, 2024
What are some Python scripts have u made for fun and daily life?
Graphics cards have been hard to find at reasonable prices here, so I made a script that ran every hour and checked the inventory of a local computer store and sent me an email if any of the models I was looking for were in stock More on reddit.com
🌐 r/Python
360
382
November 30, 2021
🌐
GitHub
gist.github.com › yohanesgultom › 630a831eff1fbdcd84b3cfec6feabe02
Random python scripts · GitHub
Save yohanesgultom/630a831eff1fbdcd84b3cfec6feabe02 to your computer and use it in GitHub Desktop. ... Embed Embed this gist in your website. Share Copy sharable link for this gist. Clone via HTTPS Clone using the web URL. ... Clone this repository at &lt;script src=&quot;https://gist.github.com/yohanesgultom/630a831eff1fbdcd84b3cfec6feabe02.js&quot;&gt;&lt;/script&gt;
🌐
Medium
medium.com › @vesper7 › 8-delightful-python-scripts-to-brighten-your-day-5908c1761905
8 Delightful Python Scripts to Brighten Your Day | by Zhongwei Li | Medium
July 30, 2023 - Copy-pasting snippets from StackOverflow only gets you so far. To take your Python skills up a level, you need a toolbox of advanced scripts that can automate tedious tasks. In this post, I’ll share 8 fun Python scripts that will brighten your mood and automate away the drudgery.
🌐
GitHub
github.com › hastagAB › Awesome-Python-Scripts
GitHub - hastagAB/Awesome-Python-Scripts: A Curated list of Awesome Python Scripts that Automate Stuffs. · GitHub
This repo is a compilation of some awesome Python scripts that automate some boring tasks or simply make our life easier...or both! ... J.A. Hernández ... Clone/Download the directory and navigate to each folder. Or... Simply navigate to the folder and download/copy the scripts!
Starred by 2.4K users
Forked by 778 users
Languages   Python 83.0% | HTML 11.5% | CSS 3.2% | JavaScript 1.9% | Jupyter Notebook 0.3% | Shell 0.1%
🌐
GitHub
github.com › topics › copy-paste
copy-paste · GitHub Topics · GitHub
Screen snip an area of your screen to have it converted to text and copied to your clipboard! python opencv machine-learning computer-vision copy paste copy-paste python-application pytesseract ... An easy to use clipboard manager made using tkinter. ... 調整段落這種煩人小事,就讓 SMARTCOPY 來為你搞定吧!! make your copy-paste-from-pdf much smarter! ... This script is used to augment image data created using LabelMe-MIT.
🌐
Python
wiki.python.org › moin › SimplePrograms
SimplePrograms - Python Wiki
What is your name?\n') number = random.randint(1, 20) print ('Well, {0}, I am thinking of a number between 1 and 20.'.format(name)) while guesses_made < 6: guess = int(input('Take a guess: ')) guesses_made += 1 if guess < number: print ('Your guess is too low.') if guess > number: print ('Your guess is too high.') if guess == number: break if guess == number: print ('Good job, {0}! You guessed my number in {1} guesses!'.format(name, guesses_made)) else: print ('Nope.
Find elsewhere
🌐
XWord Info
xwordinfo.com › Python
Sample Python Scripts, aka Fun with Word Lists
Here's a simple script you can use as a template for exploring your own word list, whether you got it from us or you built it yourself. Once you have a Python environment set up on your computer, you can copy and paste this script, change the "open" statement to point to your text file, and ...
🌐
YouTube
youtube.com › sourcegpt
cool python codes copy and paste - YouTube
Download this code from https://codegive.com Python is a versatile programming language known for its simplicity and readability. In this tutorial, we'll exp...
Published   January 19, 2024
Views   9
🌐
ActiveState
code.activestate.com › recipes › 578816-the-game-of-tic-tac-toe-in-python
The Game of Tic Tac Toe in Python « Python recipes « ActiveState Code
January 31, 2014 - Run state run recipe to run the recipe and see your changes. ... You need to put parentheses in the print argument. Darryl Jonathan Louis 6 years, 11 months ago # | flag · Yup there's something wrong you didn't put in parenthesis for print Example 'print' That you didn't do that or something please fix it quick. If you check your websites comments. Thank You ... Classic game but lacking in graphics :P Check out Tic-tac-toe in Free Python Games at http://www.grantjenks.com/docs/freegames/ You can just do "python3 -m pip install freegames" and then "python3 -m freegames.tictactoe" That includes a complete visual interface in just 57 lines of Python code!
🌐
Quora
quora.com › What-are-some-cool-Python-programs-that-require-less-than-50-lines-of-code
What are some cool Python programs that require less than 50 lines of code? - Quora
Answer (1 of 18): This image from pinterest, with all courtesy due to the maker, The Moebius Loop, geometric construction, start of 2D to 3D rendering. Mind that your vision will pl… in 2020 | Geometric shapes art, Geometric drawing, Sacred geometry art, inspired the following code.
🌐
Goglides
goglides.dev › roshan_thapa › a-collection-of-25-awesome-python-scripts-mini-projects-with-code--19nd
A Collection of 25 Awesome Python Scripts (mini projects with code ) - Goglides Dev 🌱
November 2, 2023 - import sys from selenium import webdriver from selenium.webdriver.chrome.options import Options import chromedriver_binary script_name = sys.argv[0] options = Options() options.add_argument('--headless') driver = webdriver.Chrome(options=options) try: url = sys.argv[1] driver.get(url) page_width = driver.execute_script('return document.body.scrollWidth') page_height = driver.execute_script('return document.body.scrollHeight') driver.set_window_size(page_width, page_height) driver.save_screenshot('screenshot.png') driver.quit() print("SUCCESS") except IndexError: print('Usage: %s URL' % script_name) import sys import os import shutil import pandas as pd class Split_Files: ''' Class file for split file program ''' def __init__(self, filename, split_number): ''' Getting the file name and the split index Initializing the output directory, if present then truncate it.
🌐
Reddit
reddit.com › r/python › share the code you're most proud of!
r/Python on Reddit: Share the code you're most proud of!
March 20, 2014 -

Well all know that sense of awesome when you write a neat, concise chunk of code that does something really cool. Take the code in the sidebar for example:

def fibonacci():
    a, b = 0, 1
    while 1:
        yield a
        a, b = b, a + b

It's just a thought, but if you have a moment why not share your favorite snippet of code, along with a brief explanation? It must be under 10 lines, but anything else goes. Post away!

Top answer
1 of 5
96
It's not my most favourite but it can be handy now and again from __future__ import print_function import time class timer(object): def __init__(self, func=print): self.func = func def __enter__(self): self.time = time.time() def __exit__(self, type, value, traceback): total_time = time.time() - self.time self.func(total_time) If you want to know how long some code takes to run just use with timer(): # do something and it will print out how long it took to finish whatever it was that you wanted to do. It can also take in a function as an argument time_taken = [] for i in range(1000000): with timer(time_taken.append) # do something this will add the amount of time taken each time to a list and the average time can be obtained in a similar fashion to timeit. EDIT: Added time and print_function imports as suggested below. Also this should really only be used for rough timings or where what is being timed takes milliseconds and longer to compute to account for the extra overheads involved
2 of 5
68
Generating all valid clauses of a CFG specified as BNF from itertools import chain, product from re import match, findall GRAMMAR = ''' ::= ::= "boy " | "troll " | "moon " | "telescope " ::= "hits " | "sees " ::= "runs " | "sleeps " ::= "big " | "red " ::= "quickly " | "quietly " ::= "a " | "that " | "each " | "every " ::= "he " | "she " | "it " ::= | ::= | ''' def parse(g): return dict([(w.strip(), [findall(r'(<.+?>|".+?")', s) for s in m.split('|')]) for w, m in [d.split('::=') for d in g.strip().splitlines()]]) def generate(term): return findall(r'"(.*?)"', term) if match('".*', term) else chain(*[map(''.join, product(*map(generate, p))) for p in syntax[term]]) syntax = parse(GRAMMAR) print list(generate(''))
🌐
YouTube
youtube.com › watch
The most important Python script I ever wrote - YouTube
➡ JOIN MY MAILING LISThttps://johnwr.com➡ COMMUNITYhttps://discord.gg/C4J2uckpbR➡ PROXIEShttps://proxyscrape.com/?ref=jhnwr➡ WEB SCRAPING APIhttps://hubs.li/...
Published   April 28, 2024
🌐
DataCamp
datacamp.com › tutorial › python-tips-examples
30 Cool Python Tricks For Better Code With Examples | DataCamp
October 20, 2022 - You could devise many other solutions, like calling list(a) when assigning the data to another identifier and using the copy() method. ... Our next Python tip is the easiest way to check if your data structure is empty by using the not operator.
🌐
Linux Hint
linuxhint.com › python_scripts_beginners_guide
30 python scripts examples – Linux Hint
Python is a very powerful programming language. It provides excellent control to the programmer when used in conjunction with any operating system. It is suitable for developing very simple to complex applications. In this article, 30 python scripts examples are explained with simple examples ...
🌐
Python.org
discuss.python.org › python help
Copy and Paste Files - Command - Python Help - Discussions on Python.org
June 24, 2024 - Good night people, I have a problem, I used the following code to copy and paste files from one folder to another import os import time import shutil origem = r"C:\Program Files\Corel\CorelDRAW Graphics Suite 2022\Programs64\Pasta2" destino = r"C:\Program Files\Corel\CorelDRAW Graphics Suite 2022\Programs64\Pasta1" def copy_files(origem, destino): os.makedirs(destino, exist_ok=True) for item in os.listdir(origem): origem_arquivo = os.path.join(origem, item) destino_ar...
🌐
Favtutor
favtutor.com › blog-details › 7-Python-Projects-For-Beginners
20 Exciting Python Projects for Beginners in 2023 (with Code)
This project is very significant as it will test your knowledge of various python concepts. We will build an app that any person can use to explore the file in the computer system. Also, in this project, we can add features like searching and cutting, copying, and pasting.