python tkinterのcanvasを使ってみる
最終的な基本形はこちら
座標指定は開始X,開始Y,終了X,終了Yが基本で幅、高さではないらしい
色は自在に作る場合は文字列で"#FFFFFF" RGBが16進数2桁でつながって前に#をつける
外枠を消す方法はとりあえずoutlineもfillと同じ色指定で実施
create_text の anchor="nw"は指定座標を北西 左上から文字を書いていく
python3.7.2で実施
ソースリスト
import tkinter as tk
root = tk.Tk()
root.title("Title")
root.geometry("800x450")
canvas = tk.Canvas(root, width = 800, height = 450)#Canvasの作成
canvas.create_rectangle(0, 0, 800, 450, fill = 'yellow')
canvas.create_rectangle(50, 50, 750, 400, fill = 'cyan', outline="cyan")
canvas.create_text(50, 50, text="晴天", anchor="nw", font=("HG丸ゴシックM-PRO",24), fill="#ffa000")
canvas.place(x=0, y=0)#配置位置
root.mainloop()
以下は以前pygameで作成したものを表示部分だけ移植
import tkinter
import random
class Unit:
def __init__(self,x,y,n,c):
self.x,self.y,self.n,self.c=x,y,n,c
def put(self):
global canvas
x,y=self.x,self.y
canvas.create_text(x*24+24+1, y*24+1, text=self.n, anchor="nw", font=("HG丸ゴシックM-PRO",15), fill="black")
canvas.create_text(x*24+24, y*24, text=self.n, anchor="nw", font=("HG丸ゴシックM-PRO",15), fill=cc(self.c))
def hex2(n): return ("00"+hex(n)[2:])[-2:]
def cc(rgb): return "#"+hex2(rgb[0])+hex2(rgb[1])+hex2(rgb[2])
def write_board(bd):
cs=[(0,0,0),(0,0,255),(0,255,255),(0,255,0),(0,100,0),(255,255,0),(255,0,0)]
for y in range(32):
for x in range(48):
p=x+y*48
if bd[p]>="1":
canvas.create_rectangle(x*24+24, y*24+19, x*24+24+23, y*24+19+23, fill = cc(cs[int(bd[p])]))
def bd_make():
bd=" "*48*32
for n in range(1,7):
n1=[0,30,10,20,10,10,2][n]
for i in range(n1):
x,y=random.randint(0,47-5),random.randint(0,31-5)
for x1 in range(x,x+6):
for y1 in range(y,y+6):
p=x1+y1*48
bd=bd[:p]+str(n)+bd[p+1:]
return bd
def unit_make():
units=[]
for i in range(20):
x,y=random.randint(0,47),random.randint(0,31)
t=random.randint(0,6)
n="竜鬼勇賢僧闘鰐"[t]
units+=[Unit(x,y,n,(255,255,255))]
return units
root = tkinter.Tk()
root.title("tkinterのCanvas")
root.geometry("1200x800")
canvas = tkinter.Canvas(root, width = 1200, height = 800)#Canvasの作成
bd=bd_make()
units= unit_make()
write_board(bd)
for u in units:
u.put()
canvas.place(x=0, y=0)#Canvasの配置
root.mainloop()