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()
🌐
GitHub
gist.github.com › yohanesgultom › 630a831eff1fbdcd84b3cfec6feabe02
Random python scripts · GitHub
I just was bored and I feel inspired by this https://craft.js.org/docs/overview#extensible ... from __future__ import annotations import copy import ctypes import uuid from typing import Any, Callable # ============================== # react.py # ============================== class Temp: ...
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
Python Scripts Copy Paste makes some error
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 there are indent error in my code which I couldn’t find any problem. More on discourse.mcneel.com
🌐 discourse.mcneel.com
3
0
February 15, 2024
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
Massive Python Example Script - General and Gameplay Programming | GameDev.net Forums - GameDev.net
TL;DR I am trying to make a massive example script, demonstrating all of the core syntax of Python (beginner to intermediate and maybe advanced). It could serve as a tutorial … More on gamedev.net
🌐 gamedev.net
July 29, 2015
🌐
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...
🌐
OneCompiler
onecompiler.com › python › 3wsj7ajyg
copy-paste - Python - OneCompiler
Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs. mydict = { "brand" :"iPhone", "model": "iPhone 11" } print(mydict) Following are the libraries supported by OneCompiler's Python compiler
🌐
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!
🌐
Python
wiki.python.org › moin › SimplePrograms
SimplePrograms - Python Wiki
>>> median([2, 9, 9, 7, 9, 2, 4, 5, 8]) 6 #change to 7 in order to pass the test ''' copy = sorted(pool) size = len(copy) if size % 2 == 1: return copy[int((size - 1) / 2)] else: return (copy[int(size/2 - 1)] + copy[int(size/2)]) / 2 if __name__ == '__main__': import doctest doctest.testmod() ...
Find elsewhere
🌐
OpenProcessing
openprocessing.org › sketch › 378533
the long code ive ever seen / copy and paste - Punsita Sriwachirawat - OpenProcessing
{{getLocaleDateString(sketch.createdOn, {weekday: 'long', year: 'numeric' , month: 'numeric', day: 'numeric'})}} ... As a Plus+ Member feature, this source code is hidden by the owner. ... Versions are only kept for 7 days. Join Plus+ to keep versions indefinitely! ... Any questions? Reach out via email. OK ... Oh, that naughty sketch! Please let us know what the issue is below. This is inappropriate/spam This is copyrighted material
🌐
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...
🌐
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 there are indent error in my code which I couldn’t find any problem.
🌐
W3Schools
w3schools.com › python › python_lists_copy.asp
Python - Copy Lists
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2.
🌐
Savannafiremapping
savannafiremapping.com › copy-and-paste-python
Copy and Paste python
iface = qgis.utils.iface source = QgsProject.instance().mapLayersByName(‘enter the name of the layer you are copying from here)[0] iface.setActiveLayer( source ) iface.actionCopyFeatures().trigger() target = QgsProject.instance().mapLayersByName(‘enter the name of the layer you are copying to here‘)[0] iface.setActiveLayer( target ) iface.actionPasteFeatures().trigger() target.removeSelection() iface.setActiveLayer( source ) Chnage the bold text in the above script to the appropriate file names. Now clicking the arrow button on the python consol will autmoatically save your selected features to your destination shape file.
🌐
GitHub
github.com › wangshusen › GIANT-Python-Code
GitHub - wangshusen/GIANT-Python-Code · GitHub
Contribute to wangshusen/GIANT-Python-Code development by creating an account on GitHub.
Author   wangshusen
🌐
Mathspp
mathspp.com › blog › til › 20-million-lines-of-python-code
TIL #082 – 20 million lines of Python code | mathspp
September 7, 2023 - It is a Python file with over 20 million lines of Python code. MILLION. ... I'll give you a hint. This file comes from a project called EvenOrOdd... Can you see where we are going? The file implements a single function isEven that starts like this: def isEven(num): if num == 0: return True elif num == 1: return False elif num == 2: return True elif num == 3: return False # ... If you scroll down for long enough, you'll eventually reach the end of the function, which looks like this:
🌐
CopyAssignment
copyassignment.com › python-games-code-copy-and-paste
Python Games Code | Copy and Paste – CopyAssignment
August 23, 2022 - Hello friends, today, we will see all the Python games code which you can easily copy and paste into your system.
🌐
GitHub
gist.github.com › sanchitgangwar › 2158089
Snakes Game using Python · GitHub
Snakes Game using Python. GitHub Gist: instantly share code, notes, and snippets.
🌐
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 - There will be much more commenting in the file, but for now: # -*- coding: utf-8 -*- print "Python Examples\n --By The Tutorial Doctor\n" print ("Remove tripple quotes around each secrion to test the code therein" ) ## PRINTING #--------------------------------------------------------------------- """ print 'Hello' print 'Hello','Editorial' # Concatenate/Append text (gives errors if not strings) print 'Hello' + 'Folks' print 'Hello' + ' Folks' # have to add your own space print 27 """ #--------------------------------------------------------------------- # VARIABLES #--------------------------------------------------------------------- #There are different types of variables: character, string, integer, float, boolean, array/list, dictionary, and a few others.
🌐
Automate the Boring Stuff
automatetheboringstuff.com › 2e › chapter6
Chapter 6 – Manipulating Strings
Or you could automate this task with a short Python script. The bulletPointAdder.py script will get the text from the clipboard, add a star and space to the beginning of each line, and then paste this new text to the clipboard. For example, if I copied the following text (for the Wikipedia article “List of Lists of Lists”) to the clipboard:
🌐
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.