单独的按钮来跟踪单独的值[python]

时间:2017-10-01 19:58:10

标签: python tkinter

我正在建立一个基本的python程序,用于跟踪当地Rogue Trader活动中的子弹射击。我讨厌写作 - 擦除 - 在我的表格上重写,留下污迹和粗糙。这给了我练习编码技巧的借口。最终将它保存到文件中,然后在启动时读取它们,但这是将来的。

我让它询问我有什么枪,为所述枪设置一个clipSize,然后创建一个引用每支枪的按钮。按下按钮后,fireGun应该获取与按下哪个按钮相对应的枪击值。但是,它当前的运行方式,所有枪都是从相同的弹药数量开始射击的,这是最后输入的'clipSize'。

我需要每个按钮跟踪自己的变量,以便在fireGun上更新正确的字典引用。

from tkinter import *

addGuns = 'true'
gunList = {}


while (addGuns == 'true'):

    newGun = input("What is the name of your gun? ")
    clipSize = int(input("What is its clip size? "))
    gunList[newGun] = clipSize 
    gunCheck = input("Done adding guns? ")
    if (gunCheck == 'yes'):
        addGuns = 'false'

root = Tk()
root.title("Pew Pew")

def fireGun(x):
    startingAmmo = gunList[x]
    endingAmmo = startingAmmo - 1
    gunList[x] = endingAmmo
    print(gunList[x])
    return

for gun in gunList:
    button = Button(root, text = gun, command = lambda name = gun:fireGun(gun))
    button.pack()

root.mainloop()

1 个答案:

答案 0 :(得分:0)

使用partial通过command = call将参数发送到函数。您还可以使用一个条目来获取枪支信息,并为每支枪提供一个标签,并在每个标签上标明名称和更新的弹药数量。一个非常草率的例子(我必须去上班)。

from tkinter import *
from functools import partial

gunCheck="no"
gunList = {}

while gunCheck != 'yes':
    newGun = input("What is the name of your gun? ")
    clipSize = int(input("What is its clip size? "))
    gunList[newGun] = int(clipSize)
    gunCheck = input("----->Done adding guns? ")
##    if (gunCheck == 'yes'):
##        addGuns = 'false'

root = Tk()
root.title("Pew Pew")

def fireGun(x):
    startingAmmo = gunList[x]
    endingAmmo = startingAmmo - 1
    gunList[x] = endingAmmo
    print(gunList[x])
    label_list[x].config(text=x + "-->" + str(endingAmmo))
    return

label_list={}
fr=Frame(root)
fr.pack(side="top")
for gun in gunList:
    lab=Label(fr, text="%s --> %d" %(gun, gunList[gun]))
    lab.pack(side=TOP) 
    label_list[gun]=lab
    button = Button(root, text = gun, command = partial(fireGun, gun))
    button.pack()

root.mainloop()