[英]Binding button click with command (on tkinter)
我正在编写森林火灾模拟。 代码大部分完成,结果可以在下面看到。 要开始射击,您必须输入将要燃烧的第一棵树的坐标,以使其散布。
但是,如果在指定区域找不到树,python会再次询问您有关这些坐标的信息。 因此,我希望创建一个函数来帮助我通过在tkinter窗口中单击它来选择第一棵树,而不会浪费时间找到一棵树。
您会在下面的代码部分中询问有关坐标的信息。 如果需要,我可以发布整个代码。
谢谢。
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)
因为您没有解释如何显示树,所以我举两个例子。 首先,如何获取鼠标点击的坐标:
from tkinter import *
root = Tk()
root.geometry('200x200')
def click(event):
print(event.x,event.y)
root.bind('<Button-1>', click)
root.mainloop()
其次,一种在画布上拾取对象的方法:
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.