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
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()
🌐
OneCompiler
onecompiler.com › python › 3wsj7ajyg
copy-paste - Python - OneCompiler
if conditional-expression #code elif conditional-expression #code else: #code · Indentation is very important in Python, make sure the indentation is followed correctly · For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.
Discussions

Everytime I copy and paste more than one line of code, python stops responding.
When you say you're "copy and pasting the code into Python," what exactly are you pasting the code into? Is it the REPL (the "interactive" interpreter)? If so, it's probably time for you to start looking into using a text editor/IDE to handle writing your code. More on reddit.com
🌐 r/learnpython
20
0
January 20, 2024
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
reduce time for a long for-loop in python - Stack Overflow
6681 How do I merge two dictionaries ... in Python? ... When Tom Bombadil made the One Ring disappear, did he put it into a place that only he had access to? How to check if an SSM2220 IC is authentic and not fake? ... Keyboard shortcut for evaluating the current cell while keeping the cursor in the cell more hot questions ... To subscribe to this RSS feed, copy and paste this URL into ... More on stackoverflow.com
🌐 stackoverflow.com
November 13, 2011
How to paste Python code in Stack Overflow without DIY - Meta Stack Overflow
Here is an image of correct code (in fact, code of a previous question): If I copy this code and paste it in a code sample in this editor, I got this (another image): So I'm obliged to add a tab ... More on meta.stackoverflow.com
🌐 meta.stackoverflow.com
🌐
Stack Overflow
stackoverflow.com › questions › 75464439 › can-i-paste-a-long-code-in-a-loop-in-python
Can I paste a long code in a loop in python - Stack Overflow
if you have a 200 line code and you want to paste in a loop, how would you do it, without ruining the loop i tried this: code = [ your 200 line code ] while True: if example = example ...
🌐
Python
wiki.python.org › moin › SimplePrograms
SimplePrograms - Python Wiki
# indent your Python code to put into an email from pathlib import Path python_files = Path().glob('*.py') for file_name in sorted(python_files): print (f' ------{file_name}') with open(file_name) as f: for line in f: print (' ' + line.rstrip()) print()
🌐
GitHub
gist.github.com › yohanesgultom › 630a831eff1fbdcd84b3cfec6feabe02
Random python scripts · GitHub
from __future__ import annotations import copy import ctypes import uuid from typing import Any, Callable # ============================== # react.py # ============================== class Temp: ...
🌐
OpenProcessing
openprocessing.org › sketch › 378533
the long code ive ever seen / copy and paste - Punsita Sriwachirawat - OpenProcessing
CC {{sketch.licenseObject.short}} · This sketch is created with an older version of Processing, and doesn't work on browsers anymore
Find elsewhere
🌐
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...
🌐
Mathspp
mathspp.com › blog › til › 20-million-lines-of-python-code
TIL #082 – 20 million lines of Python code | mathspp
September 7, 2023 - What is more, I was able to write this blog post and the testing of the function isEven is still running (the for loop I shared above), so I'll interrupt that loop: >>> for i in range(2 ** 20): ... assert EvenOrOdd.isEven(i) == (not (i % 2)) ... ^CTraceback (most recent call last): File "<stdin>", line 2, in <module> KeyboardInterrupt >>> i 475308 · So, as you can see, I've gone through 46% of the faster test cases. At least we know that the numbers up to 475,307 are correctly classified as even or odd by the function isEven. Every Monday, you'll get a Python deep dive that unpacks a topic with analogies, diagrams, and code examples so you can write clearer, faster, and more idiomatic code.
🌐
Python Forum
python-forum.io › thread-31517.html
How to paste several lines of codes to the Python console
I'm not sure in which part of the forum to post this (as this is not really code related). I used to be able to do this until very recently. Now when I try to paste several lines at once I get the error message: Quote:SyntaxError: multiple statement...
🌐
W3Schools
w3schools.com › python › python_lists_copy.asp
Python - Copy Lists
Python Operators Arithmetic Operators Assignment Operators Comparison Operators Logical Operators Identity Operators Membership Operators Bitwise Operators Operator Precedence Code Challenge Python Lists · Python Lists Access List Items Change List Items Add List Items Remove List Items Loop Lists List Comprehension Sort Lists Copy Lists Join Lists List Methods List Exercises Code Challenge Python Tuples
🌐
Automate the Boring Stuff
automatetheboringstuff.com › 2e › chapter6
Chapter 6 – Manipulating Strings
You already know how to concatenate two string values together with the + operator, but you can do much more than that. You can extract partial strings from string values, add or remove spacing, convert letters to lowercase or uppercase, and check that strings are formatted correctly. You can even write Python code to access the clipboard for copying and pasting text.
🌐
Sololearn
sololearn.com › en › Discuss › 2830510 › solved-python-coding-project-longest-word
(SOLVED) Python Coding Project: Longest word
Sololearn is the world's largest community of people learning to code. With over 25 programming courses, choose from thousands of topics to learn how to code, brush up your programming knowledge, upskill your technical ability, or stay informed about the latest trends.
🌐
Sustainabilitymethods
sustainabilitymethods.org › index.php › Loops_in_Python
Loops in Python - Sustainability Methods
The range() function is often used with a for loop to generate a sequence of numbers, especially when the number of iterations is known.
🌐
GitHub
gist.github.com › sanchitgangwar › 2158089
Snakes Game using Python · GitHub
there is an integer error in line 29 (win.timeout(150 - (len(snake)/5 + len(snake)/10)0). correct line is [ (win.timeout(int(150 - (len(snake)/5 + len(snake)/10)0))]. code needs integer initialization for the defined numerical values. ... every time i try to make it work... this happens: Traceback (most recent call last): File "C:/Users/Maria Jose/Documents/home/Python/snake game try cp.py", line 4, in import curses File "C:\Users\Maria Jose\AppData\Local\Programs\Python\Python38\lib\curses__init__.py", line 13, in from _curses import * ModuleNotFoundError: No module named '_curses'
🌐
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 - 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!
🌐
McNeel Forum
discourse.mcneel.com › scripting
Python Scripts Copy Paste makes some error - Scripting - McNeel Forum
February 15, 2024 - I’m teaching students about Automating Architectural Design in Rhino + python. I wrote some well made codes with methods and break it into long code just to show them. But the problem window in component told me that t…
🌐
GameDev.net
gamedev.net › home › forums › programming › general and gameplay programming › massive python example script
Massive Python Example Script - General and Gameplay Programming | GameDev.net Forums - GameDev.net
July 29, 2015 - ##### ### WHILE LOOP age = 0 old_age = 30 while age < old_age: print 'Still young @ ' + str(age) age = age + 1 if age == old_age: print "You've reached the pinnacle @ " + str(age) ##### ### FUNCTIONS # A function is a group of statements IamCool = True ### BUILT-IN FUNCTIONS # print() - Prints values to the screen print(name) print(favorite_number) # Two ways to print print height print IamCool,",I am cool" print array_of_colors print array_of_numbers # raw_input() - Gets input from the user occupation = raw_input('What is your occupation?