0

I followed a few tutorials and I am trying to implement a clean object oriented code for python gui. The idea of my project is opening an image and drawing circles on it with mouse click.

There are 2 issues:

1) In the code below, the canvas does not render the image.the image should be taken from the user

In java there is a repaint function that is called by VM so that the contents of the frame can be updated. I couldn't find something in python (No, I am not willing to try adding timer function to redraw every second.)

2) Besides HELLO is not printed even I press f key. The keylistener is also not working

I have done GUI with Java before but Python code looks very dirty comparing Java. I would be grateful if you can help.

from tkinter import *
from PIL import Image, ImageTk
from tkinter import Tk, Canvas, Frame, BOTH
from tkinter import filedialog

class Example(Frame):

    def __init__(self, container):
        super().__init__()
        self.container = container
        self.canvas = None
        self.initUI()

    def initUI(self):
        fname=filedialog.askopenfilename(title='"pen')
        self.canvas = Canvas(self.container)
        self.canvas.pack(anchor='nw', fill='both', expand=1)
        self.canvas.focus_set()
        self.canvas.bind("<ButtonRelease-1>", self.mouseReleased)
        self.canvas.bind("<Key>", self.pressedkey)

        image = Image.open(fname)
        image = image.resize((400, 400))
        image = ImageTk.PhotoImage(image)
        image_id=self.canvas.create_image(0, 0, image=image, anchor='nw')

    def mouseReleased(self, event):
        self.canvas.create_oval(event.x-10, event.y-10, event.x+10, event.y+10, width=2, fill='blue')

    def pressedkey(self,event):
        pressedkey=str(repr(event.char))
        print(pressedkey,type(pressedkey))
        if pressedkey.__eq__("f"):
            print("HELLO")

def main():
    root = Tk()
    ex = Example(root)
    root.geometry("400x250+300+300")
    root.mainloop()


if __name__ == '__main__':
    main()

  • 1
    The first issue is the same as this [question](https://stackoverflow.com/questions/16424091/why-does-tkinter-image-not-show-up-if-created-in-a-function). – acw1668 May 04 '22 at 05:39
  • 1
    To fix second issue, try calling `root.wait_visibility()` before creating instance of `Example` class because there may be weird issue when `askopenfilename()` dialog is open before the root window is ready. Also to fix the comparison issue, `processkey=event.char` should be called instead. – acw1668 May 04 '22 at 05:40
  • Thank you so much. I solved using your advice acw1668 – PolatAlemdar May 05 '22 at 01:29

0 Answers0