from tkinter import *
import tkinter as tk
class Paint():
def __init__(self):
self.window=Tk()
self.sizex=500
self.sizey=500
self.canvas = Canvas(self.window, width=self.sizex, height=self.sizey, bg="white")
self.canvas.pack()
self.img = PhotoImage(width=self.sizex, height=self.sizey)
self.canvas.create_image((self.sizex, self.sizey), image=self.img, state="normal")
self.canvas.bind("<Button-1>",self.color_in)
def color_in(self, event):
self.img.put("black", (event.x, event.y))
paint=Paint()
mainloop()
In the code above, I can get a blank white window to open, but when I click anywhere on the screen there is no change. How do I get the window to update?
Couple of things:
You should only import Tkinter once. If you import it as "tk" your code will be easier to understand.
If you set different colors to the different widgets it will be easy to see if they are where you want them to be.
When you place the image on the canvas you put it at position 500, 500 which is in the lower right corner. The default anchor is at the center of the image. This results in you only seeing the upper left 1/4 of the image, as Bryan points out.
I have repositioned the image to (0,0) and assigned the upper left corner ('nw') as anchor. Also canvas highlightthickness=0
removes a 2 pixel highlight border from the canvas. Image state='normal'
is the default.
Lastly I made the mark placed on the image a bit larger to make it easier to see. And I adjusted the call to mainloop()
The image updates automatically, now that it's in the right position.
import tkinter as tk
class Paint():
def __init__(self):
self.window = tk.Tk()
self.sizex = 500
self.sizey = 500
self.canvas = tk.Canvas(self.window, width=self.sizex,
height=self.sizey, highlightthickness=0)
# Set canvas background color so you can see it
self.canvas.config(bg="thistle")
self.canvas.pack()
self.img = tk.PhotoImage(width=self.sizex, height=self.sizey)
self.canvas.create_image((0,0), image=self.img, state="normal",
anchor='nw')
# Set image color so you can see it
self.img.put('khaki',to=(0, 0, self.sizex, self.sizey))
self.canvas.bind("<Button-1>",self.color_in)
def color_in(self, event):
# Paint a 2x2 square at the mouse position on image
x, y = event.x, event.y
self.img.put("black", to=(x-2, y-2, x+2, y+2))
paint = Paint()
paint.window.mainloop()