2017-03-26 59 views
1

我正在做一個小外星人項目來幫助學習tkinter中的圖形,我遇到了一個問題。我試圖讓外星人的眼球保持在眼睛內部,但仍然會移動,但這需要我檢測眼球的邊緣,這是一個圓圈。不太確定tkinter中的座標怎麼樣(除了基礎),所以任何幫助表示讚賞。謝謝!Tkinker圍繞圓圈座標處​​理蟒蛇3

from tkinter import * 
from threading import Timer 
import random 
import time 
global canvas, root 

root = Tk() 
root.title("Alien") 
root.attributes("-topmost", 1) 

canvas = Canvas(root, height=300, width =400) 
canvas.pack() 
Blinking = False 

class Alien: 
    def __init__(self): 
     global canvas, root 
     self.body = canvas.create_oval(100,150,300,250, fill = "green") 
     self.eye = canvas.create_oval(170,70,230,130, fill = "white") 
     self.eyeball = canvas.create_oval(190,90,210,110, fill = "black") 
     self.mouth = canvas.create_oval(150,220,250,240, fill = "red") 
     self.neck = canvas.create_line(200,150,200,130) 
     self.hat = canvas.create_polygon(180,75,220,75,200,20, fill = "blue") 
     self.words = canvas.create_text(200,800, text = "I'm an alien!", anchor="nw") 
     root.update() 

    def openMouth(self): 
     global canvas, root 
     canvas.itemconfig(self.mouth, fill = "black") 
     root.update() 
    def closeMouth(self): 
     global canvas, root 
     canvas.itemconfig(self.mouth, fill = "red") 
     root.update() 

    def burp(self, event): 
     self.openMouth() 
     canvas.itemconfig(self.words, text = "BURRRRP!") 
     time.sleep(0.5) 
     self.closeMouth() 
    def moveEye(self,event): 
     global root, canvas 
     canvas.move(alien.eyeball , random.randint(-1,1) , random.randint(-1,1)) 
     root.update() 

    def blink(self,event): 
     canvas.itemconfig(self.eye, fill = "green") 
     canvas.itemconfig(self.eyeball, state=HIDDEN) 
     Blinking = True 
     root.update() 
    def unblink(self,event): 
     canvas.itemconfig(self.eye, fill = "white") 
     canvas.itemconfig(self.eyeball, state=NORMAL) 
     Blinking = False 
     root.update() 



alien = Alien() 
alien.openMouth() 
time.sleep(1) 
alien.closeMouth() 
canvas.bind_all("<Button-1>", alien.burp) 
canvas.bind_all("<KeyPress-a>", alien.blink) 

Timer(2, alien.moveEye).start() 
while not Blinking: 
    alien.moveEye(event) 
    if alien.moveEye.event.x > 190: 
     canvas.move(alien.eyeball, -1 , 0) 
+0

你能在幾何術語解釋現實問題? (我從來沒有見過外星人:)) – MBo

+0

一個圓圈隨着另一個圓圈內的隨機算法移動,我需要設置參數,因此它不能逃脫圓圈。所以也許有一個方程來檢測圓周的座標(r平方的平方根減x平方?)?謝謝 :) –

回答

0

半徑爲r小圓位於半徑爲R的大圈子裏面,如果

(BigCenter.X - SmallCenter.x)^2 + (BigCenter.Y - SmallCenter.Y)^2 < (R - r)^2 

^2表示平方值