python - 如果我将 tkinter 对象放在函数中,为什么 x 和 y 坐标不会与您单击的位置对齐?
问题描述
我不明白为什么会发生这种情况,但是如果我将 tkinter 对象放在函数中,x 和 y 坐标将无法正确对齐。
这是代码
from tkinter import *
import random
root = Tk()
root.title("Treasure Hunt")
root.geometry("400x300")
root.iconbitmap("treasure2.ico")
class Treasure_game:
count = 0
search = 1
def __init__(self, main, num1, num2):
self.num1 = num1
self.num2 = num2
frame = Frame(main)
frame.pack()
self.treasure_map = Canvas(frame, bg="#f3c474", width=200, height=200)
self.treasure_map.create_rectangle(2, 2, 201, 201)
self.treasure_map.bind("<Button-1>", self.game)
self.top_label = Label(frame, text="Click on the map to find the treasure")
self.coord_label = Label(frame)
self.parrot_button = Button(frame, text="Search", state=DISABLED, command=self.parrot_search)
self.top_label.pack()
self.treasure_map.pack()
self.coord_label.pack()
self.parrot_button.pack()
def game(self, event):
text = (f"You clicked at x: {event.x} y: {event.y}. You are {abs(event.x-x_coord)} away from x and {abs(event.y-y_coord)} from y.")
self.coord_label.config(text=text)
self.count += 1
if abs(event.x-x_coord) < 5 and abs(event.y-y_coord) < 5:
self.coord_label.config(text="You have found the treasure!")
self.top_label.config(text="You have won!!")
self.treasure_map.create_line(self.num1-5, self.num2-5, self.num1+5, self.num2+5, fill="red", width=2)
self.treasure_map.create_line(self.num1-5, self.num2+5, self.num1+5, self.num2-5, fill="red", width=2)
print(f"It took {self.count} tries to find the treasure")
self.playing = False
if self.count >= 10 and self.search == 1:
self.parrot_button["state"] = NORMAL
def parrot_search(self):
if self.search == 1:
self.treasure_map.create_oval(self.num1-random.randint(20, 40), self.num2-random.randint(20, 40), self.num1+random.randint(20, 40), self.num2+random.randint(20, 40))
self.count += 1
self.search -= 1
def main_game():
pass
x_coord = random.randint(3, 200)
y_coord = random.randint(3, 200)
game = Treasure_game(root, x_coord, y_coord)
main_game()
root.mainloop()
如果我将 x_coord、y_coord 和游戏变量放在 main_game 函数中,Treasure_game 的 num1 和 num2 将不会与您点击的位置对齐。
解决方案
因此,由于x_coord
您y_coord
在Treasure_game()
.
我们改变main_game
def main_game():
x_coord = random.randint(3, 200)
y_coord = random.randint(3, 200)
game = Treasure_game(root, x_coord, y_coord)
我们更改了 if 语句,因为当我们初始化 Class 时,我们设置了self.num1 = num1
whichnum1
是x_coord
if abs(event.x-self.num1) < 5 and abs(event.y-self.num2) < 5:
#continue with the other code
推荐阅读
- java - 使用 Spring Data JPA 时如何处理 ObjectOptimisticLockingFailureException 和 StaleObjectStateException?
- javascript - 为什么这个 js 文件中有类型,为什么它在 react js 应用程序中有效,但在 react ts 应用程序中无效?
- wordpress - 带有我自己的主题的 Elementor Pro 主题构建器不能一起工作
- java - 使用 Spring JPA/Hibernate 按不同值批量更新
- swift - 更新到 Xcode 12 beta 6 后解析服务器不兼容的指针错误
- c# - System.Net.Mail.SmtpClient.Send 在本地主机上成功但在服务器上失败
- bash - 如何将每个 for 循环的输出粘贴为 bash 中的新列
- excel - 我如何在 vba 中使用 ADODB 连接
- python - Plotly:如何更改沿 x 轴的时间分辨率?
- moodle - Moodle - 关于向 Unity 内容发送数据