今天從下午忙到如今,睡覺。json
這個能繪點圖的。app
import json import tkinter as tk from tkinter import filedialog from tkinter import LabelFrame from tkinter import StringVar from PIL import Image, ImageTk # 方塊大小 card_size = 120 # 繪圖起點座標 start_x = 400 start_y = 100 # 7 * 5 方格 x_grid = 7 y_grid = 5 # 打開文件,載入json文件 def open_file(): fname = filedialog.askopenfilename(title='打開文件', filetypes=[('json', '*.json'), ('All Files', '*')]) # 更新Label text變量 var.set(fname) with open(fname, 'r') as load_f: global card_dict card_dict = json.load(load_f) # 繪圖 def draw_card(): # 這個打開文件,用的是回調函數,我暫時也不知道如何不用這個全局變量 global card_dict imgs_list = [] for i in range(y_grid): y1 = start_y + i * card_size for j in range(x_grid): x1 = start_x + j * card_size # 解析json裏對應的文件名 image_num = card_dict[str(i+1)][str(j+1)] image_path = "images/{}-{}.png".format(image_num[0], image_num[1]) # 載入圖片 img = Image.open(image_path) # 重定義大小 img = img.resize((card_size, card_size), Image.BILINEAR) # 重定義旋轉 img = img.rotate(image_num[2]) imgs = ImageTk.PhotoImage(img) # 必定要放在列表裏,要否則,後面的圖會刷掉前面的圖 imgs_list.append(imgs) # 每一次都全繪已有圖片 for item in imgs_list: # 以nw左上角爲基準點 cv.create_image((x1, y1), anchor='nw', image=item) # 不調用update,不會更新畫布 win.update() # 停一秒再做下一步動做 win.after(1000) # 不讓圖消失太快 win.after(10000) win = tk.Tk() win.title('tkinter') w = win.winfo_screenwidth() h = win.winfo_screenheight() win.geometry("%dx%d" % (w, h)) cv = tk.Canvas(win, bg='silver', width=w, height=h) # 要更新label的text,要用var.set方法才行 var = StringVar() var.set("...") lab_fra = LabelFrame(win, height=200, width=300, text='選擇文件') lab_fra.pack(side='top', fill='both', expand=True) btn_open = tk.Button(lab_fra, text='打開文件', command=open_file) btn_open.grid(row=0, column=0) btn_render = tk.Button(lab_fra, text='開始渲染', command=draw_card) btn_render.grid(row=0, column=1) text_label = tk.Label(lab_fra, textvariable=var) text_label.grid(row=0, column=2) # 畫格子, 要算好橫縱座標 for i in range(y_grid): y1 = start_y + i * card_size for j in range(x_grid): x1 = start_x + j * card_size cv.create_rectangle(x1, y1, x1 + card_size, y1 + card_size) cv.pack() win.mainloop()
json文件格式:ide
{ "1": { "1": ["0001","a", 0],"2": ["0002", "b", 0],"3": ["0003", "a", 0],"4": ["0004", "a", 0], "5": ["0005", "b",40],"6": ["0006","b",180],"7": ["0006","b",90] }, "2": { "1": ["0001","b", 0],"2": ["0002", "a", 20],"3": ["0003", "a", 0],"4": ["0004", "a", 0], "5": ["0005", "a",20],"6": ["0006","b",0],"7": ["0006","b",90] }, "3": { "1": ["0001","a", 0],"2": ["0002", "a", 0],"3": ["0003", "a", 0],"4": ["0004", "a", 0], "5": ["0005", "a",0],"6": ["0006","a",0],"7": ["0006","b",90] }, "4": { "1": ["0001","b", 0],"2": ["0002", "a", 0],"3": ["0003", "b", 0],"4": ["0004", "a", 0], "5": ["0005", "a",0],"6": ["0006","a",0],"7": ["0006","b",90] }, "5": { "1": ["0001","a", 0],"2": ["0002", "a", 0],"3": ["0003", "a", 0],"4": ["0004", "a", 0], "5": ["0005", "a",0],"6": ["0006","a",0],"7": ["0006","b",90] } }
繪出來的樣子:函數