简体   繁体   English

用命令单击绑定按钮(在tkinter上)

[英]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. 但是,如果在指定区域找不到树,python会再次询问您有关这些坐标的信息。 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. 因此,我希望创建一个函数来帮助我通过在tkinter窗口中单击它来选择第一棵树,而不会浪费时间找到一棵树。

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

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

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