Я осматривался несколько часов и не смог найти решения этой конкретной проблемы. Я видел одного человека, который задал тот же вопрос, но не предоставил кода и поэтому не получил ответа. Моя проблема заключается в следующем:
У меня есть программа, которая случайным образом отправляет черепаху влево и вправо в течение заданного количества ходов. Поворотная часть работает, но когда я пытаюсь сохранить холст, она сохраняет только видимую часть, из-за чего часто что-то обрезается. Я пробовал увеличить размер холста настройки, а также снимок экрана, но сохраненный файл всегда оказывается в верхнем левом углу и поэтому обрезается. Я прикрепляю всю свою программу (она короткая, не волнуйтесь), потому что я не уверен, какой именно аспект нужно изменить.
Буду очень признателен за любую помощь!
import turtle
import random
'''
Takes a variable, number, of how many random turns the turtle should make and a variable filenumber,
which is used to save multiple different iterations of the program per program execution
'''
def left_or_right(number,filenumber):
# Counters to make sure the turtle doesn't turn too many times
count = 0
subright = 0
subleft = 0
#sets up screen
win_width, win_height, bg_color = 10000, 10000,'white'
turtle.setup()
turtle.screensize(win_width, win_height,bg_color)
# Clears the screen, sets the turtle in the middle of the screen, drops the pen and hides the
# Turtle. If you want to see the turtles do the drawing, turn turtle.tracer to True, and
# uncomment out turtle.speed('fastest')
turtle.clear()
turtle.home()
turtle.hideturtle()
turtle.pendown()
turtle.speed('fastest')
turtle.tracer(False)
# A for loop for the turtle's turns
for i in range(number):
# Calls decider to you can get a random direction every time
decider = random.randint(0, 1)
# in order to minimize the turtle just going around in circles,
# if the turtle has made more that 3 of the same turn, turn it the other way
# the next to if statements deal with the turtle turning right too many times
if decider == 1 and subright 3:
turtle.left(90)
turtle.forward(20)
count += 1
subright = 0
# The next two if statements make sure the turtle doesn't turn right too many times
elif decider == 0 and subleft 3:
turtle.right(90)
turtle.forward(20)
count += 1
subleft = 0
# if the number of turns is equal to what the user inputed, stop making the turns
# and update the screen
if count == number:
turtle.penup()
turtle.update()
# Take a screen capture of the screen and saves it to where the python file is
ts = turtle.getscreen()
ts.getcanvas().postscript(file=filenumber,height=10000, width=10000)
# turtle.done() is here as a debugging tool. If you set the number of files you're
# generating to one, you can keep the turtle window open to check that the file correctly
# copied the turtle screen
#turtle.done()
''' Takes a variable, filenumber, which is the number of generated files you want'''
def filegen(filenumber):
for i in range(filenumber):
# Calls the left or right function as many times as you told it to
# Note: this is where the left or right function get's its turn number parameters
left_or_right(10000,i)
def main():
# calls filegen as many times as you want it to
filegen(4)
if __name__ == '__main__':
main()
Подробнее здесь: https://stackoverflow.com/questions/647 ... ire-canvas
Сохранение большого графического изображения черепахи со всего холста. ⇐ Python
Программы на Python
1766865102
Anonymous
Я осматривался несколько часов и не смог найти решения этой конкретной проблемы. Я видел одного человека, который задал тот же вопрос, но не предоставил кода и поэтому не получил ответа. Моя проблема заключается в следующем:
У меня есть программа, которая случайным образом отправляет черепаху влево и вправо в течение заданного количества ходов. Поворотная часть работает, но когда я пытаюсь сохранить холст, она сохраняет только видимую часть, из-за чего часто что-то обрезается. Я пробовал увеличить размер холста настройки, а также снимок экрана, но сохраненный файл всегда оказывается в верхнем левом углу и поэтому обрезается. Я прикрепляю всю свою программу (она короткая, не волнуйтесь), потому что я не уверен, какой именно аспект нужно изменить.
Буду очень признателен за любую помощь!
import turtle
import random
'''
Takes a variable, number, of how many random turns the turtle should make and a variable filenumber,
which is used to save multiple different iterations of the program per program execution
'''
def left_or_right(number,filenumber):
# Counters to make sure the turtle doesn't turn too many times
count = 0
subright = 0
subleft = 0
#sets up screen
win_width, win_height, bg_color = 10000, 10000,'white'
turtle.setup()
turtle.screensize(win_width, win_height,bg_color)
# Clears the screen, sets the turtle in the middle of the screen, drops the pen and hides the
# Turtle. If you want to see the turtles do the drawing, turn turtle.tracer to True, and
# uncomment out turtle.speed('fastest')
turtle.clear()
turtle.home()
turtle.hideturtle()
turtle.pendown()
turtle.speed('fastest')
turtle.tracer(False)
# A for loop for the turtle's turns
for i in range(number):
# Calls decider to you can get a random direction every time
decider = random.randint(0, 1)
# in order to minimize the turtle just going around in circles,
# if the turtle has made more that 3 of the same turn, turn it the other way
# the next to if statements deal with the turtle turning right too many times
if decider == 1 and subright 3:
turtle.left(90)
turtle.forward(20)
count += 1
subright = 0
# The next two if statements make sure the turtle doesn't turn right too many times
elif decider == 0 and subleft 3:
turtle.right(90)
turtle.forward(20)
count += 1
subleft = 0
# if the number of turns is equal to what the user inputed, stop making the turns
# and update the screen
if count == number:
turtle.penup()
turtle.update()
# Take a screen capture of the screen and saves it to where the python file is
ts = turtle.getscreen()
ts.getcanvas().postscript(file=filenumber,height=10000, width=10000)
# turtle.done() is here as a debugging tool. If you set the number of files you're
# generating to one, you can keep the turtle window open to check that the file correctly
# copied the turtle screen
#turtle.done()
''' Takes a variable, filenumber, which is the number of generated files you want'''
def filegen(filenumber):
for i in range(filenumber):
# Calls the left or right function as many times as you told it to
# Note: this is where the left or right function get's its turn number parameters
left_or_right(10000,i)
def main():
# calls filegen as many times as you want it to
filegen(4)
if __name__ == '__main__':
main()
Подробнее здесь: [url]https://stackoverflow.com/questions/64745710/saving-a-large-turtle-graphics-image-from-the-entire-canvas[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия