python-turtle模块-创建虚拟按钮-实现按钮功能 点击”按钮“后触发对应功能
使用turtle模块的时候,有时需要创建“按钮”,但是据我所知,turtle似乎还没有按钮的创建方法,所以,我想到了利用鼠标点击位置来实现一个虚拟的 “按钮”!上代码:
先导入
import turtle as t#为了让大家阅读方便,没有from turtle import *
一些基本的设置
t.color('#FF0033');t.pu();t.ht();t.speed(0);t.title('模拟按钮')#比较简单,初学者也能看懂,所以用了分号
开始画按钮
def 画退出按钮():
t.goto(10,10);t.pd();t.goto(10,40);t.goto(40,40)
t.goto(40,10);t.goto(10,10);t.pu();t.goto(26,16)
t.write('退出',align="center", font=("微软雅黑",11,"bold"))
画退出按钮()
虚拟按钮被点击
def coordinate(x,y):
print('鼠标点击:X坐标:{} Y坐标:{}'.format(x,y));
if x>10 and y>10 and x<40 and y<40:t.bye();print('事件:退出')
t.onscreenclick(coordinate)
结束
t.done()
运行
图片:
代码:
import turtle as t
t.color('#FF0033');t.pu();t.ht();t.speed(0);t.title('模拟按钮')
def 画退出按钮():
t.goto(10,10);t.pd();t.goto(10,40);t.goto(40,40);t.goto(40,10);t.goto(10,10);t.pu();t.goto(26,16)
t.write('退出',align="center", font=("微软雅黑",11,"bold"))
画退出按钮()
def coordinate(x,y):
print('鼠标点击:X坐标:{} Y坐标:{}'.format(x,y));
if x>10 and y>10 and x<40 and y<40:t.bye();print('事件:退出')
t.onscreenclick(coordinate)
t.done()
代码图片:
这个"退出"按钮会了,其他还不会吗?以此类推!
来都来了,给个👍吧!