简体   繁体   English

python tkinter canvas 根据选定的 combobox 值使用多个条件移动图像

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

Please see the image for your reference Hello 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.请查看图片以供参考您好我正在制作我的tkinter毕业设计,我是python的新手。我想根据所选的combobox值从1到5将指定的棋子移动到风险矩阵可能性和影响矩阵中。如果1是从impact box中选择的,5是从likelihood box中选择的,棋子会移动到主canvas中相应的矩阵框架。我在web中进行了研究,我只能使用猴子修补方法移动一个条件. However, I have other 24 conditions, the monkey patching will only work on one or the last if condition.但是,我还有其他 24 个条件,猴子修补程序只会对一个或最后一个 if 条件起作用。 I have tried multiple elif statements but to no avail.我尝试了多个 elif 语句但无济于事。 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]

 

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.然后每次调用move_image时,您都可以使用这些字典来移动棋子。 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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM