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
Python Online Compiler & Interpreter
Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast.
Discussions

100% complete noob trying to copy/paste code
You can't do that! To understand where the syntax error is, you have to know what it is! You can't just copy paste random codes from different places and make a program out of that. I want to help you, but you'll need to study my help. Look for asset lines, lines that mark a file, if you don't have the file, your program won't recognize it. Also look for missing modules, you may be using commands from a module you don't have or that you didn't activated. To activate a module write 'from (module) import *'. You have to download a module before trying that. Look for wrong spaces too, copy/paste is dangerous because of spaces, between symbols. That's why I don't recommend it More on reddit.com
🌐 r/learnpython
22
0
September 12, 2021
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
3
0
June 24, 2024
terminal - Copy & paste Python code into the command line - Unix & Linux Stack Exchange
When I paste several lines at once in a Python3.9 session in the terminal in my Mac it does not understand that they are different lines, and it fails: Python 3.9.1 (default, Jan 8 2021, 17:17:17) [Clang 12.0.0 (clang-1200.0.32.28)] on darwin Type "help", "copyright", "credits" or "license" ... More on unix.stackexchange.com
🌐 unix.stackexchange.com
January 26, 2021
Copy and paste the following code into your Python editor.
Question - Copy and paste the following code into your Python editor. - . Find the answer to this and other Programming questions on JustAnswer More on justanswer.co.uk
🌐 justanswer.co.uk
1
January 26, 2021
🌐
Python Morsels
pythonmorsels.com › paste
Python Pastebin: Share Python Code
A free Python-oriented pastebin service for sharing Python code snippets with anyone
🌐
Reddit
reddit.com › r/learnpython › 100% complete noob trying to copy/paste code
r/learnpython on Reddit: 100% complete noob trying to copy/paste code
September 12, 2021 -

[SOLVED]

Yo. Please use the most dumbed down language, because I've literally never done this stuff, Idk how python works. And at this moment, I'm not exactly trying to. Im just trying to copy/paate a command. I am simply trying to copy/paste code from a guide and it keeps saying I have a syntax error. I think I figured out that you dont actually type the $, but I dont even know if that's correct. Either way, I continue to get a syntax error with the arrow pointing to seemingly random letters.

Please help.

Edit: This is the simple command given to download a HTTP library for Python called "Requests":

$ python -m pip install requests

Edit2: Thanks to social_nerdtastic for answering. I just had to use cmd. I had a feeling it was something simple and fundamental that I just didn't know

🌐
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...
🌐
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: ...
Find elsewhere
🌐
Anirudh Jayaraman
pythonandr.com › 2015 › 05 › 16 › code-for-my-first-text-based-game
Code for my First Text-Based Game – Anirudh Jayaraman
July 6, 2015 - Here’s the python code for this text-based game you might want to try out. You can simply copy the code below into a text file, naming it something like game.py and save it to your home directory or wherever you wish to and run game.py from. Then from Terminal (CMD for Windows), type in python game.py.
🌐
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 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.
🌐
Python
wiki.python.org › moin › SimplePrograms.html
SimplePrograms
import unittest def median(pool): 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 class TestMedian(unittest.TestCase): def testMedian(self): self.assertEqual(median([2, 9, 9, 7, 9, 2, 4, 5, 8]), 7) if __name__ == '__main__': unittest.main()
🌐
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 - Python · Tcl · Komodo IDE | more ▼ · Lists · Support · PPM Index · PyPM Index · Welcome, guest | Sign In | My Account | Store | Cart · ActiveState Code » Recipes · Languages Tags Authors Sets · I thought this is a fun game to program. Easy to program and can teach a lot. Captain DeadBones · Copy to Clipboard ·
🌐
GitHub
gist.github.com › sanchitgangwar › 2158089
Snakes Game using Python · GitHub
Snakes Game using Python. GitHub Gist: instantly share code, notes, and snippets.
🌐
Cliprun
cliprun.com › python-code-runner
Python Code Runner - Online & Free
Write code in a modern editor, import popular libraries like pandas and NumPy without setup, and run your code with a single click. Free to use and perfect for both quick tests and longer coding sessions. ... Enter Python code or paste the code you want to run.
🌐
Quora
quora.com › How-do-I-make-a-game-in-Python-copy-paste
How to make a game in Python copy paste - Quora
Answer (1 of 3): You have to decide what to copy and paste - this is not really a Python question; it is a software design question. what data do you need to ‘copy’, how does the user select what to copy, when the user pastes how do they identify where the data is pasted ?
🌐
Ray
ray.so
Create beautiful images of your code
Turn your code into beautiful images. Choose from a range of syntax colors, hide or show the background, and toggle between a dark and light window.
🌐
Codingem
codingem.com › home › how to copy text to clipboard in python
How to Copy Text to Clipboard in Python - codingem.com
October 15, 2022 - software development and tech. By Artturi Jalli · To copy text to the clipboard in Python, use the pyperclip module. Before you can use the module, you need to install it with: pip install pyperclip · Then you can use its copy() method to ...
🌐
Open Source Initiative
opensource.org › license › mit
The MIT License – Open Source Initiative
March 30, 2026 - Copyright Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software…
🌐
Note.nkmk.me
note.nkmk.me › home › python
Copy and Paste Text to the Clipboard with pyperclip in Python | note.nkmk.me
January 30, 2024 - Refer to the official documentation for details. Not Implemented Error — Pyperclip 1.5 documentation · Use pyperclip.copy() to copy text to the clipboard. ... Use pyperclip.paste() to paste (get) text from the clipboard.
🌐
X
x.com › mvanhorn › status › 2035857346602340637
Matt Van Horn on X: "https://t.co/AwabaZTtdp" / X
JavaScript is not available · We’ve detected that JavaScript is disabled in this browser. Please enable JavaScript or switch to a supported browser to continue using x.com. You can see a list of supported browsers in our Help Center · Help Centre · Terms of Service Privacy Policy Cookie ...