提问人:Elle 提问时间:11/15/2023 最后编辑:furasElle 更新时间:11/16/2023 访问量:22
如何在窗口中创建可单击 graphics.py 按钮?
How can I create a clickable button in graphics.py window?
问:
我正在尝试制作一个游戏,并让开始屏幕有一个按钮,您可以单击该按钮开始玩游戏。
我尝试过,但我不确定如何合并它。我可以使用该语句还是必须使用其他语句?clickPoint=getMouse()
while True
答:
0赞
furas
11/16/2023
#1
从理论上讲,它是使用它创建的,但其工作方式与它不同,它可以使直接使用的问题。zella graphics
tkinter
tkinter.Button(..., command=function)
zella graphics
tkinter
tkinter.Button()
zella graphics
此时,唯一的想法是使用(或)并检查您是否单击了按钮的矩形内部。while True
getMouse()
checkMouse()
from graphics import *
win = GraphWin("My Buttons", 200, 200)
c = Rectangle(Point(50,50), Point(150,100))
c.setFill('Red')
c.draw(win)
while True:
clickPoint = win.getMouse()
if (c.getP1().getX() <= clickPoint.getX() <= c.getP2().getX()
and c.getP1().getY() <= clickPoint.getY() <= c.getP2().getY()):
print('Red Button Clicked')
break
win.close()
如果你有很多按钮,那么你可以创建一个新的类(使用'Rectangle),并检查它是否被点击。Button
class Button(Rectangle):
def isClicked(self, point):
return (self.getP1().getX() <= point.getX() <= self.getP2().getX()
and self.getP1().getY() <= point.getY() <= self.getP2().getY())
或更短
class Button(Rectangle):
def isClicked(self, point):
return (self.p1.x <= point.x <= self.p2.x
and self.p1.y <= point.y <= self.p2.y)
现在需要更短的代码if
from graphics import *
class Button(Rectangle):
def isClicked(self, point):
#return (self.getP1().getX() <= point.getX()<= self.getP2().getX()
# and self.getP1().getY() <= point.getY() <= self.getP2().getY()
return (self.p1.x <= point.x <= self.p2.x
and self.p1.y <= point.y <= self.p2.y)
# --- main ---
win = GraphWin("My Buttons", 200, 200)
c = Button(Point(50,50), Point(150,100))
c.setFill('Red')
c.draw(win)
d = Button(Point(50,100), Point(150,150))
d.setFill('Green')
d.draw(win)
while True:
clickPoint = win.getMouse()
if c.isClicked(clickPoint):
print('Red Button Clicked')
break
if d.isClicked(clickPoint):
print('Green Button Clicked')
break
win.close()
评论
zella graphics
与所有其他 GUI 框架不同,我认为您必须在内部使用并检查您是否单击了正确的位置。clickPoint = getMouse()
while True:
zella graphics
tkinter
tkinter.Button(..., command=function)
zella graphics
tkinter
tkinter.Button()
Graphics