简体   繁体   中英

Binding button click with command (on tkinter)

I am coding a simulation of a fire in a forest. The code is mostly done and the result can be seen below. To start the fire, you have to input the coordinates of the first tree that will burn, so that it can spread around.

However, python will ask you again and again about these coordinates if a tree is not found in the designated area. Hence, I am looking to create a function that would help me to choose the first tree by clicking on it in a tkinter window and not lose time finding a tree.

You will find below the part of the code that asks about the coordinates. If needed, I can post the whole code.

Thanks.

def take_input():
while 1:
    print("The coordinates to start the fire are :")
    debut =int(input("x= "))
    debutbis=int(input("y= "))
    xx=T[debut]
    yy=T[debut][debutbis]
    if yy == 0:
        print("Error, no tree found.")
    elif debut < 0 or debut >= len(T) or debutbis < 0 or debutbis >= len(T[0]):
        print("Error")
    else:
        break
app.after(200, burn_forest, debut, debutbis)

Since you are not explaining how you display trees I'll give you two examples. First how to get the coordinates of a mouse cilck:

from tkinter import *

root = Tk()
root.geometry('200x200')

def click(event):
    print(event.x,event.y)

root.bind('<Button-1>', click)
root.mainloop()

Second, a way to pick objects on a canvas:

import tkinter as tk
import random

def on_click(event):
    current = event.widget.find_withtag("current")
    if current:
        item = current[0]
        color = canvas.itemcget(item, "fill")
        label.configure(text="you clicked on item with id %s (%s)" % (item, color))
    else:
        label.configure(text="You didn't click on an item")

root = tk.Tk()
label = tk.Label(root, anchor="w")
canvas = tk.Canvas(root, background="bisque", width=400, height=400)
label.pack(side="top", fill="x")
canvas.pack(fill="both", expand=True)

for color in ("red", "orange", "yellow", "green", "blue", "violet"):
    x0 = random.randint(50, 350)
    y0 = random.randint(50, 350)
    canvas.create_rectangle(x0, y0, x0+50, y0+50, outline="black", fill=color)
    canvas.bind('<ButtonPress-1>', on_click)

root.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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