簡體   English   中英

用命令單擊綁定按鈕(在tkinter上)

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM