Tkinter动态按钮运行相同的代码

时间:2017-04-15 01:28:44

标签: python tkinter

我正在寻找修复代码的方法。 我有一些代码将显示一个tkinter窗口,其中包含运行代码的按钮。 但是......问题是,无论按哪个按钮,它都会运行相同的代码行。

这是我的代码: Crbnk.py :(主文件)

import tkinter
import draw
import ast

#Setup
oldtiledat = None
window = tkinter.Tk()
window.title("CarbonOS 0.1 (BETA)")
window.geometry("1080x720")
tiledat = {}
tiles = []

#Clears tiles. Arguments: Tile List.
def clearTiles(tl):
    for x in tl:
        x.destroy()
        tl.remove(x)

#Redraws tiles. Arguments: Tile List, Tile Metadata. Returns new tile list
def updateTiles(tl,tls):
    clearTiles(tl)
    length = len(list(tls.keys()))
    return draw.draw(window,list(tls.keys()),list(tls.values()),range(length))

#Loads tiles. Arguments: File to load from
def loadtiles(tilefile):
    with open(tilefile,"r") as tf:
        lines = tf.readlines()
        ret = lines[0]
        ret = ret.rstrip("\n")
        ret = ast.literal_eval(ret)
    return ret

#Dumps tiles to a file. Arguments: File to write, data to save.
def savetiles(tilefile,tiledata):
    with open(tilefile,"w") as tf:
        tf.write(str(tiledata))

#Init

#get tiles into memory
tiledat = loadtiles("tile.cov")


while True:
    #Update
    window.update()

    #TileMgr (Updates if needed so no flicker)
    if oldtiledat != tiledat:
        tiles = updateTiles(tiles,tiledat)
        oldtiledat = tiledat

tile.cov(磁贴存储文件):

{"This Prints Hi":"print('hi')","This Prints Hello":"print('hello')"}

draw.py(tile API):

import tkinter

def draw(window,names,cmd,lst):
    allb = []
    for y in lst:
        b = tkinter.Button(window, text=names[y], command=lambda: eval(cmd[y]))
        print(cmd[y])
        b.pack(side=tkinter.LEFT,anchor=tkinter.N)
        allb.append(b)
    return allb

提前致谢!

0 个答案:

没有答案