Уведомления

Группа в Telegram: @pythonsu

#1 Ноя. 10, 2018 09:47:57

lada0807
Зарегистрирован: 2018-04-17
Сообщения: 19
Репутация: +  0  -
Профиль   Отправить e-mail  

Python поставить фоновую картинку

Кто может поставить на фон любую картинку
Вот ЛИСТИНГ

 from tkinter import *
import random
# Globals
WIDTH = 800
HEIGHT = 600
SEG_SIZE = 20
IN_GAME = True
# Helper functions
def create_block():
    """ Creates an apple to be eaten """
    global BLOCK
    posx = SEG_SIZE * random.randint(1, (WIDTH-SEG_SIZE) / SEG_SIZE)
    posy = SEG_SIZE * random.randint(1, (HEIGHT-SEG_SIZE) / SEG_SIZE)
    BLOCK = c.create_oval(posx, posy,
                          posx+SEG_SIZE, posy+SEG_SIZE,
                          fill="red")
def main():
    """ Handles game process """
    global IN_GAME
    if IN_GAME:
        s.move()
        head_coords = c.coords(s.segments[-1].instance)
        x1, y1, x2, y2 = head_coords
        # Check for collision with gamefield edges
        if x2 > WIDTH or x1 < 0 or y1 < 0 or y2 > HEIGHT:
            IN_GAME = False
        # Eating apples
        elif head_coords == c.coords(BLOCK):
            s.add_segment()
            c.delete(BLOCK)
            create_block()
        # Self-eating
        else:
            for index in range(len(s.segments)-1):
                if head_coords == c.coords(s.segments[index].instance):
                    IN_GAME = False
        root.after(100, main)
    # Not IN_GAME -> stop game and print message
    else:
        c.create_text(WIDTH/2, HEIGHT/2,
                      text="GAME OVER!",
                      font="Arial 20",
                      fill="red")
class Segment(object):
    """ Single snake segment """
    def __init__(self, x, y):
        self.instance = c.create_rectangle(x, y,
                                           x+SEG_SIZE, y+SEG_SIZE,
                                           fill="white")
class Snake(object):
    """ Simple Snake class """
    def __init__(self, segments):
        self.segments = segments
        # possible moves
        self.mapping = {"Down": (0, 1), "Right": (1, 0),
                        "Up": (0, -1), "Left": (-1, 0)}
        # initial movement direction
        self.vector = self.mapping["Right"]
    def move(self):
        """ Moves the snake with the specified vector"""
        for index in range(len(self.segments)-1):
            segment = self.segments[index].instance
            x1, y1, x2, y2 = c.coords(self.segments[index+1].instance)
            c.coords(segment, x1, y1, x2, y2)
        x1, y1, x2, y2 = c.coords(self.segments[-2].instance)
        c.coords(self.segments[-1].instance,
                 x1+self.vector[0]*SEG_SIZE, y1+self.vector[1]*SEG_SIZE,
                 x2+self.vector[0]*SEG_SIZE, y2+self.vector[1]*SEG_SIZE)
    def add_segment(self):
        """ Adds segment to the snake """
        last_seg = c.coords(self.segments[0].instance)
        x = last_seg[2] - SEG_SIZE
        y = last_seg[3] - SEG_SIZE
        self.segments.insert(0, Segment(x, y))
    def change_direction(self, event):
        """ Changes direction of snake """
        if event.keysym in self.mapping:
            self.vector = self.mapping[event.keysym]
# Setting up window
root = Tk()
root.title("PythonicWay Snake")
c = Canvas(root, width=WIDTH, height=HEIGHT, bg="#003300")
c.grid()
# catch keypressing
c.focus_set()
# creating segments and snake
segments = [Segment(SEG_SIZE, SEG_SIZE),
            Segment(SEG_SIZE*2, SEG_SIZE),
            Segment(SEG_SIZE*3, SEG_SIZE)]
s = Snake(segments)
# Reaction on keypress
c.bind("<KeyPress>", s.change_direction)
create_block()
main()
root.mainloop()

Прикреплённый файлы:
attachment f7181bcfb704c0c1d784e2195f163485.png (341,5 KБ)

Офлайн

#2 Ноя. 10, 2018 12:13:13

rami
Зарегистрирован: 2018-01-08
Сообщения: 281
Репутация: +  72  -
Профиль   Отправить e-mail  

Python поставить фоновую картинку

Переписать строку кода:

 c = Canvas(root, width=WIDTH, height=HEIGHT)  #убрать цвет: bg="#003300"

сразу за ней добавить две строки кода:
 img = PhotoImage(file='f7181bcfb704c0c1d784e2195f163485.png')
c.create_image(0, 0, image=img, anchor='nw')

Офлайн

#3 Ноя. 11, 2018 06:26:32

lada0807
Зарегистрирован: 2018-04-17
Сообщения: 19
Репутация: +  0  -
Профиль   Отправить e-mail  

Python поставить фоновую картинку

rami
c.create_image(0, 0, image=img, anchor='nw')
Спасибо огромное братан, прям выручил. А то я на ютубе столько роликов посмотрел ничё не понятно. Скажи а если я в папку закину свою прогу когда скомпилирую и туда же рисунок фоновый надо? если да то как потом путь к рисунку прописывать?

Офлайн

Board footer

Модераторировать

Powered by DjangoBB

Lo-Fi Version