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()