pythoncanvasmovepatchmonkey

python tkinter canvas moving an image using multiple condition based on selected combobox values


Please see the image for your referenceHello I am making my tkinter graduation project, I am new to python. I want to move the specified chess piece inside a risk matrix likelihood and impact matrix based on the selected combobox values from 1 to 5. If 1 is selected from impact box and 5 is selected from likelihood box, the chess piece would move to the corresponding matrix frame in the main canvas. I have made a research in the web and I was able to move only one condition using monkey patching method. However, I have other 24 conditions, the monkey patching will only work on one or the last if condition. I have tried multiple elif statements but to no avail. I would like someone to help me with this problem.

import tkinter as tk
from PIL import Image, ImageDraw, ImageFont, ImageTk
from tkinter import tkk
from tkinter import *


def abs_move(self, canvas, _object, new_x, new_y, speed=10):
    
    
    global chesspiece
    # Get the current object position
    x, y, *_ = self.bbox(_object)
    # Move the object
    self.move(_object, new_x-x, new_y-y)
# Monkey patch the `abs_move` method
tk.Canvas.abs_move = abs_move
def on_button_pressed(event):
    global canvas
    global chesspiece
    start_x = canvas.canvasx(event.x)
    start_y = canvas.canvasy(event.y)
    print("start_x, start_y =", start_x, start_y)

"""
Testing script:
"""
# Moves image based on conditional coordintaes
def move_image():
    global canvas
    global chesspiece
    if combo_impact.get() and combo_likelihood.get() != '':
        

        totalvalues = int(impactDict[combo_impact.get()]) * int(likelihoodDict[combo_likelihood.get()])
        
    total.configure(text="Risk score : " + str(totalvalues))

    #this where I want to increase addition 24 if conditions
    #like if combo_impact.get() == 2 and combo_likelihood.get() == 1: etc
    if combo_impact.get() == 1 and combo_likelihood.get() == 1:
        return "negligible risk"
                   
    canvas.abs_move(canvas, chesspiece, 180, 208)

    
    
impactDict = {'Catstrophic': 5, 'Severe': 4, 'Major': 3, 'Moderate': 2, 'Minor':1}
likelihoodDict = {'Almost Certain': 5, 'likely': 4, 'possible': 3, 'unlikely': 2, 'rare':1}
root = tk.Tk()
root.geometry("1356x750")
root.state("zoomed")
root.configure(bg='Dodgerblue4')
canvas = tk.Canvas(root, width=650, height=450,bg="black")
canvas.grid(row=3, column=5, pady=20)
button = tk.Button(root, text="RATE", command=move_image)
button.grid(row=2, column=0)
img2 = ImageTk.PhotoImage(file="65.png")
image_on_canvas = canvas.create_image(0, 0, image=img2, anchor='nw')
canvas.bind("<Button-1>", on_button_pressed)
risklevel = ImageTk.PhotoImage(file="king5.png")
chesspiece= canvas.create_image(93,302,image=risklevel)

tk.Label(root, text='legal Risk Impact', bd=3, bg='Dodgerblue4', fg='white').grid(row=0, column=0)
var_impact = tk.StringVar()
combo_impact = ttk.Combobox(root, values=list(impactDict.keys()), justify="center", textvariable=var_impact)
combo_impact.bind('<<ComboboxSelected>>', lambda event: impact_level.config(text=impactDict[var_impact.get()]))
combo_impact.grid(row=0, column=1)
combo_impact.current(0)

impact_level = tk.Label(root, text="", bg='Dodgerblue4', fg='white')
impact_level.grid(row=0, column=2, padx=10)

tk.Label(root, text='Legal risk Likelihood', bd=3, bg='Dodgerblue4', fg='white').grid(row=1, column=0)
var_likelihood = tk.StringVar()
combo_likelihood = ttk.Combobox(root, values=list(likelihoodDict.keys()), justify="center", textvariable=var_likelihood)
combo_likelihood.bind('<<ComboboxSelected>>', lambda event: likelihood_level.config(text=likelihoodDict[var_likelihood.get()]))
combo_likelihood.grid(row=1, column=1)
combo_likelihood.current(0)

likelihood_level = tk.Label(root, text="", bg='Dodgerblue4', fg='white')
likelihood_level.grid(row=1, column=2, padx=10)

totalvalues = 'None'
total = tk.Label(root,text="", bg='Dodgerblue4', fg='white' )
total.grid(row=2, column=1, padx=5, pady=5)


root.mainloop()[1]

 

Solution

  • To fix the issue of moving pieces around, I'd create additional dictionaries using the same keys as these two:

    impactDict = {'Catstrophic': 5, 'Severe': 4, 'Major': 3, 'Moderate': 2, 'Minor':1}
    likelihoodDict = {'Almost Certain': 5, 'likely': 4, 'possible': 3, 'unlikely': 2, 'rare':1}
    

    but with the values set to the coordinates for where you'd like to move the piece. Then each time move_image is called, you can use those dictionaries to move the piece. Here's an example of what I mean:

    def move_image():
        global canvas
        global chesspiece
        likelyhoodDict_x = {'Almost Certain': 560, 'likely': 465, 'possible': 365, 'unlikely': 270, 'rare': 170}
        impactDict_y = {'Catstrophic': 0, 'Severe': 50, 'Major': 100, 'Moderate': 150, 'Minor': 208}
        likelyhood = combo_likelihood.get()
        impact = combo_impact.get()
        if impact != '' and likelyhood != '':
            totalvalues = int(impactDict[combo_impact.get()]) * int(likelihoodDict[combo_likelihood.get()])
    
        total.configure(text="Risk score : " + str(totalvalues))
    
        if likelyhood in likelyhoodDict_x and impact in impactDict_y:
            canvas.abs_move(canvas, chesspiece, likelyhoodDict_x[likelyhood], impactDict_y[impact])
    
        if impact == 'Minor' and likelyhood == 'rare':
            return "negligible risk"