【问题标题】:How to create randomly colored text in Trinket.io/Python?如何在 Trinket.io/Python 中创建随机颜色的文本?
【发布时间】:2021-04-14 05:48:05
【问题描述】:

我正在制作一款名为 Gravity code 的游戏,该游戏的目标是捕捉掉落的物品,这些物品会改变乌龟的颜色、速度、大小或形状。我需要一个随机颜色的标题。

# --- imports ---

import turtle
from random import * 

# --- variables ---

font_setup = ("Verdana", 25, "normal")
screen = turtle.Screen()

# --- main ---

title.speed("fastest")
title.hideturtle()
title.penup()
title.goto(-62, 60)
title.write("Gravity", font = font_setup)
title.setpos(-45, 30)
title.write("Code", font = font_setup)

# --- events ---

screen.mainloop()

【问题讨论】:

  • 使用turtle.onclickturtle.onscreenclick在点击时执行函数并检查鼠标位置是否在按钮的矩形内。
  • @Tibebes.M 可以是传送门trinket.io
  • @Tibebes.M 很久以前有类似的repl.it 但现在看来你必须创建帐户
  • 我只使用 Turtle 来绘制像 this gallery 这样的图形,我不确定 onclick 是如何工作的。通常我会使用PyGame,它使用矩形来绘制按钮并将这个矩形保持为两个角-left, topx1,y1)和right, bottomx2, y2)然后你检查(left < mouse_x < right) and (top < mouse_y < bottom)
  • @Tibebes.M 谢谢,turtle 非常适合绘制人物 - 但不适用于游戏 :) 在子页面中,我有此画廊中每张图片的代码。

标签: python python-2.7 pygame


【解决方案1】:

点击button时可以使用turtle.onclick(function, mouse_button)执行函数。

onclick 只需要没有() 的函数名(所谓的“回调”)

on_button_click 必须获得两个值 - 鼠标位置。

import turtle

# --- functions ---

def on_button_click(x, y):
    print('button clicked:', x,y)
    button.hideturtle()
    
# --- main ---
    
screen = turtle.Screen()
button = turtle.Turtle()

button.speed("fastest")
#screen.addshape("icons8-button-100.png") #It's the second button.
#button.shape("icons8-button-100.png") #https://icons8.com/icons/set/button
button.left(90) # The second image is the button I'm using.
button.penup() #It can be resized afer you click download to...
button.goto(0, -120) # 70 x 70 pixels.

button.onclick(on_button_click, 1)

screen.mainloop()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-20
    • 2011-05-13
    • 2015-04-26
    • 1970-01-01
    • 1970-01-01
    • 2016-02-28
    • 1970-01-01
    • 2021-05-21
    相关资源
    最近更新 更多