首页 > 解决方案 > 如果我将 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 将不会与您点击的位置对齐。

标签: pythontkinter

解决方案


因此,由于x_coordy_coordTreasure_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 = num1whichnum1x_coord

if abs(event.x-self.num1) < 5 and abs(event.y-self.num2) < 5:
    #continue with the other code

推荐阅读