職案人

求職・歴史・仏教などについて掲載するつもりだが、自分の思いつきが多いブログだよ。適当に付き合って下さい。

オーバーライド機能

2017年12月08日 | Python
オーバーライド機能

【環境条件】
OS:Windows 10
Python 3.6.1

【オーバーライド機能リスト】
オーバーライド機能や継承を使ってみた。では「example07-09-01.py」を覗いて見る。

# coding:utf-8
import tkinter as tk

#円クラス
class Ball:←基本クラス
def __init__(self, x, y, dx, dy, color):
self.x = x
self.y = y
self.dx = dx
self.dy = dy
self.color = color

#moveメソッドは円、四角、三角共通
def move(self, canvas):
# いまの円を消す
self.erase(canvas)
# X座標、Y座標を動かす
self.x = self.x + self.dx
self.y = self.y + self.dy
# 次の位置に円を描画する
self.draw(canvas)
# 端を超えていたら反対向きにする
if (self.x >= canvas.winfo_width()):
self.dx = -1
if (self.x <= 0):
self.dx = 1
if (self.y >= canvas.winfo_height()):
self.dy = -1
if (self.y <= 0):
self.dy = 1

#図形を消す処理
def erase(self, canvas):←オーバーライド:円を消す
canvas.create_oval(self.x - 20, self.y - 20, self.x + 20, self.y + 20, fill="white", width=0)

  #図形を描画する処理
def draw(self, canvas):←オーバーライド:円を描く
canvas.create_oval(self.x - 20, self.y - 20, self.x + 20, self.y + 20, fill=self.color, width=0)

#四角クラス
#継承は、class 新しいクラス名(基本クラス)
class Rectangle(Ball):←派生クラス

def erase(self, canvas):←オーバーライド:四角を消す
canvas.create_rectangle(self.x - 20, self.y - 20, self.x + 20, self.y + 20, fill="white", width=0)

def draw(self, canvas):←オーバーライド:四角を描く
canvas.create_rectangle(self.x - 20, self.y - 20, self.x + 20, self.y + 20, fill=self.color, width=0)

#三角クラス(円の派生クラス)
#継承は、class 新しいクラス名(基本クラス)
class Triangle(Ball):←派生クラス

def erase(self, canvas):←オーバーライド:三角を消す
canvas.create_polygon(self.x, self.y - 20, self.x + 20, self.y + 20, self.x - 20, self.y + 20, fill="white", width=0)

def draw(self, canvas):←オーバーライド:三角を描く
canvas.create_polygon(self.x, self.y - 20, self.x + 20, self.y + 20, self.x - 20, self.y + 20, fill=self.color, width=0)

# 円、四角形、三角形を、まとめて用意する
balls = [
Ball(400, 300, 1, 1, "red"),
Rectangle (200, 100, -1, 1, "green"),
Triangle(100, 200, 1, -1, "blue")
]
def loop():
# 動かす
for b in balls:
b.move(canvas)
# もう一回
root.after(10,loop)

# ウィンドウを描く
root = tk.Tk()
root.geometry("600x400")
root.title("オーバーライド")

# Canvasを置く
canvas =tk.Canvas(root, width =600,height = 400, bg="#fff")
canvas.place(x = 0, y = 0)

# タイマーをセット
root.after(10, loop)

root.mainloop()

【起動】
「example07-09-01.py」ファイルを起動すると
コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする