今天从下午忙到现在,睡觉。
这个能绘点图的。
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文件格式:
{ "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] } }
绘出来的样子: