python - Tkinter 复选框命令

标签 python tkinter

我正在用 Python 设计《龙与地下城》的角色表,并使用 Tkinter 来处理图形界面。但是,如果与相同技能对应的复选框处于事件状态,我想将一个元素(在本例中为技能的“熟练程度”)添加到列表中。 复选框按钮适用于某些命令,例如退出(“root.destroy”),但这似乎没有任何作用。 我创建了一个角色类,该角色有一个空的熟练程度列表,为了向其添加熟练程度,我创建了一个函数,只要匹配的复选框值设置为 True(“1”),该函数就会执行此操作

import tkinter as tk

def modifier(score):
    score = int(score)

    return (score - 10) // 2

class Character:   
    proficiencies = []

    abilities = {"Strength": 12, "Dexterity": 16, "Constitution": 14, "Intelligence": 10, "Wisdom": 16, "Charisma": 9}        

    skills = {"Athletics": 0, "Acrobatics": 0, "Sleight of Hand": 0, "Stealth": 0, "Arcana": 0,  "History": 0,
              "Investigation": 0, "Nature": 0, "Religion": 0,"Animal Handling": 0, "Insight": 0, "Medicine": 0, 
              "Perception": 0, "Survival": 0, "Deception": 0, "Intimidation": 0, "Performance": 0, "Persuasion": 0}

counter = 0 
variables = []
skills = []

root = tk.Tk()

def addSkill():
    if exec("var" + str(counter) + ".get() == 1"):
        Character.proficiencies.append(skills[counter].replace('_', ' '))
    elif exec("var" + str(counter) + ".get() == 0"):
        pass

for skill in sorted(Character.skills.keys()): 
    skills.append(skill.replace(" ", "_"))
    exec("var" + str(counter) + " = tk.IntVar()")
    exec(skill.replace(" ", "") + "= tk.Checkbutton(root, text=skill, variable = var" + str(counter) + ", command = addSkill)")
    exec(skill.replace(" ", "") + ".pack()")    
    variables.append("var" + str(counter))

    counter += 1

counter = 0

root.mainloop()

index = 0

for skill in Character.skills:
        if index == 0:
            ability = "Strength"

        elif index >= 1 and index <= 3:
            ability = "Dexterity"

        elif index >= 4 and index <= 8:
            ability = "Intelligence"

        elif index >= 9 and index <= 13:
            ability = "Wisdom"

        elif index >= 14:
            ability = "Charisma"            

        if skill in Character.proficiencies:
            Character.skills[skill] = 10 + (modifier(Character.abilities[ability]) + 2) * 2
        else:
            Character.skills[skill] = 10 + modifier(Character.abilities[ability]) * 2  

        index += 1     

最佳答案

这是遵循 Bryan Oakley 建议避免使用 exec() 并且不动态创建命名变量的示例,我想您会同意它比您的代码更容易阅读和理解在哪里使用。

import tkinter as tk


SKILL_NAMES = ('Athletics', 'Acrobatics', 'Sleight of Hand', 'Stealth', 'Arcana',
               'History', 'Investigation', 'Nature', 'Religion', 'Animal Handling',
               'Insight', 'Medicine', 'Perception', 'Survival', 'Deception',
               'Intimidation', 'Performance', 'Persuasion')

class Character:
    proficiencies = []
    abilities = {"Strength": 12, "Dexterity": 16, "Constitution": 14,
                 "Intelligence": 10, "Wisdom": 16, "Charisma": 9}
    skills = dict.fromkeys(SKILL_NAMES, 0)


def modifier(score):
    return (int(score) - 10) // 2


root = tk.Tk()

# Create tk.IntVars for holding value of each skill.
skill_vars = {skill: tk.IntVar() for skill in Character.skills}

# tkinter Checkbutton callback.
def addSkill(skill, var):
    """ Add skill to proficiencies if Checkbutton is now checked. """
    if var.get() == 1:
        Character.proficiencies.append(skill)

# Create a Checkbutton corresponding to each skill.
for skill in Character.skills:
    btn = tk.Checkbutton(root, text=skill, variable=skill_vars[skill],
                command=lambda name=skill, var=skill_vars[skill]: addSkill(name, var))
    btn.pack()


root.mainloop()


for index, skill in enumerate(Character.skills):
    if index == 0:
        ability = "Strength"
    elif 1 <= index <= 3:
        ability = "Dexterity"
    elif 4 <= index <= 8:
        ability = "Intelligence"
    elif 9 <= index <= 13:
        ability = "Wisdom"
    elif index >= 14:
        ability = "Charisma"

    if skill in Character.proficiencies:
        Character.skills[skill] = 10 + (modifier(Character.abilities[ability]) + 2) * 2
    else:
        Character.skills[skill] = 10 + modifier(Character.abilities[ability]) * 2

关于python - Tkinter 复选框命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54526368/

相关文章:

python - 使用队列导致异步异常 "got Future <Future pending> attached to a different loop"

python - 通过 SSH 连接到 EBS 创建的 EC2 实例

python - 只应打开一扇 window 时却打开了两扇 window

python - 嵌入超过 280 个元素的 Canvas 中的 Tkinter 网格的意外行为

Python 3.5 Tkinter如何将字典保存到文件

python - 使用 Python 高效查找部分字符串匹配 --> 从 5 GB 文件中的值列表开始的值

python - Django:如何使表单有条件?

python - 如何在 python 中将多个导入放在一行中

python - 如何实时更新tkinter标签文本

python - 设置手形光标以选取 matplotlib 文本