[英]Creating a Button (from image) in Zelle's Graphics
我有一個開始按鈕圖像,試圖將其轉換為程序中的按鈕。 但是,我認為我做錯了數學或顯然有錯,因為它不起作用。 基本上,我要嘗試的是如果該人單擊該按鈕,它將啟動一個if語句。 有任何想法嗎? 提前致謝!
#Assigning Mouse x,y Values
mousePt = win.getMouse()
xValue = startImage.getHeight()
yValue = startImage.getWidth()
#Assigning Buttons
if mousePt <= xValue and mousePt <= yValue:
hour = 2
startImage是我要創建按鈕的圖像。 hour是其他代碼中聲明的變量。
您正在將蘋果與橙子進行比較。 這行:
if mousePt <= xValue and mousePt <= yValue:
大致等於說:
if Point(123, 45) <= 64 and Point(123, 45) <= 64:
將點與寬度和高度進行比較是沒有意義的。 您需要將寬度和高度與圖像的中心位置結合起來,並從鼠標位置提取X和Y值:
from graphics import *
win = GraphWin("Image Button", 400, 400)
imageCenter = Point(200, 200)
# 64 x 64 GIF image from http://www.iconsdb.com/icon-sets/web-2-green-icons/video-play-icon.html
startImage = Image(imageCenter, "video-play-64.gif")
startImage.draw(win)
imageWidth = startImage.getWidth()
imageHeight = startImage.getHeight()
imageLeft, imageRight = imageCenter.getX() - imageWidth/2, imageCenter.getX() + imageWidth/2
imageBottom, imageTop = imageCenter.getY() - imageHeight/2, imageCenter.getY() + imageHeight/2
start = False
while not start:
# Obtain mouse Point(x, y) value
mousePt = win.getMouse()
# Test if x,y is inside image
x, y = mousePt.getX(), mousePt.getY()
if imageLeft < x < imageRight and imageBottom < y < imageTop:
print("Bullseye!")
break
win.close()
這個特殊的圖標顯示為一個圓形,您可以單擊的區域包括其矩形邊界框,其中一些位於圓形之外。 可以將點擊次數限制為完全可見的圖像,但這需要更多工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.