python-3.x 如何在tkinter中填充由循环创建的输入框

m4pnthwp  于 2023-04-13  发布在  Python
关注(0)|答案(1)|浏览(187)

基本上,我创建了许多输入框,我想在点击特定按钮时填充它,但当我这样做时,它只填充最后一个。我知道我可以一个接一个地创建框,但有没有办法这样做。

def Roll_Dice(Dice):
    if Dice=="d6":
        Rolls=[]
        for i in range(0,4):
            Rolls.append(random.randint(1,6))
        return Rolls
    elif Dice=="d20":
        return random.randint(1,20)
def check(name):
    if name=="Str":
        StrDice.append(Roll_Dice("d6"))
        StrRoll.config(state="disabled")
        Fill(name,StrDice)
def Fill(stat,list):
    if stat=="Str":
        for i in range(0,4):
            strength.insert(i,list[i])
STR=LabelFrame(root,text="Str")
STR.place(x=10,y=10)
j=0
for i in range(0,4):
    j+=1
    strength=Entry(STR)
    strength.grid(row=j,column=0,pady=5)
STATS=Frame(root)
STATS.place(x=10,y=150)
StrRoll=Button(STATS,text="Roll for your Str stats",command=lambda:check("Str"))
StrRoll.grid(row=0,column=0,columnspan=1,padx=2)

以下是我的全部代码:

from tkinter import*
import functions
import random
root=Tk()
StrDice=[]
DexDice=[]
IntDice=[]
ConsDice=[]
WisDice=[]
CharDice=[]
def Roll_Dice(Dice):
    if Dice=="d6":
        Rolls=[]
        for i in range(0,4):
            Rolls.append(random.randint(1,6))
        return Rolls
    elif Dice=="d20":
        return random.randint(1,20)
def check(name):
    if name=="Str":
        StrDice.append(Roll_Dice("d6"))
        StrRoll.config(state="disabled")
        Fill(name,StrDice)
    elif name=="Dex":
        DexDice.append(Roll_Dice("d6"))
        DexRoll.config(state="disabled")
    elif name=="Int":
        IntDice.append(Roll_Dice("d6"))
        IntRoll.config(state="disabled")
    elif name=="Cons":
        ConsDice.append(Roll_Dice("d6"))
        ConsRoll.config(state="disabled")
    elif name=="Wis":
        WisDice.append(Roll_Dice("d6"))
        WisRoll.config(state="disabled")
    else:
        CharDice.append(Roll_Dice("d6"))
        CharRoll.config(state="disabled")
def Fill(stat,list):
    if stat=="Str":
        for i in range(0,4):
            strength.insert(i,list[i])
    pass
Stats=["Str","Dex","Int","Cons","Wis","Char"]
STR=LabelFrame(root,text="Str")
STR.place(x=10,y=10)
j=0
for i in range(0,4):
    j+=1
    strength=Entry(STR)
    strength.grid(row=j,column=0,pady=5)
DEX=LabelFrame(root,text="Dex")
DEX.place(x=140,y=10)
j=0
for i in range(0,4):
    j+=1
    Dexterity=Entry(DEX)
    Dexterity.grid(row=j,column=0,pady=5)
INT=LabelFrame(root,text="Int")
INT.place(x=270,y=10)
j=0
for i in range(0,4):
    j+=1
    Intelligence=Entry(INT)
    Intelligence.grid(row=j,column=0,pady=5)
CONS=LabelFrame(root,text="Cons")
CONS.place(x=400,y=10)
j=0
for i in range(0,4):
    j+=1
    Constitution=Entry(CONS)
    Constitution.grid(row=j,column=0,pady=5)
WIS=LabelFrame(root,text="Wis")
WIS.place(x=530,y=10)
j=0
for i in range(0,4):
    j+=1
    Wisdom=Entry(WIS)
    Wisdom.grid(row=j,column=0,pady=5)
CHAR=LabelFrame(root,text="Char")
CHAR.place(x=660,y=10)
j=0
for i in range(0,4):
    j+=1
    Charisma=Entry(CHAR)
    Charisma.grid(row=j,column=0,pady=5)
STATS=Frame(root)
STATS.place(x=10,y=150)
StrRoll=Button(STATS,text="Roll for your Str stats",command=lambda:check("Str"))
StrRoll.grid(row=0,column=0,columnspan=1,padx=2)
DexRoll=Button(STATS,text="Roll for your Dex stats",command=lambda:check("Dex"))
DexRoll.grid(row=0,column=1,columnspan=1,padx=2)
IntRoll=Button(STATS,text="Roll for your Int stats",command=lambda:check("Int"))
IntRoll.grid(row=0,column=2,columnspan=1,padx=2)
ConsRoll=Button(STATS,text="Roll for your Cons stats",command=lambda:check("Cons"))
ConsRoll.grid(row=0,column=3,columnspan=1,padx=2)
WisRoll=Button(STATS,text="Roll for your Wis stats",command=lambda:check("Wis"))
WisRoll.grid(row=0,column=4,columnspan=1,padx=2)
CharRoll=Button(STATS,text="Roll for your Char stats",command=lambda:check("Char"))
CharRoll.grid(row=0,column=5,columnspan=1,padx=2)

root.mainloop()
wko9yo5t

wko9yo5t1#

你可以做很多事情来简化你想要实现的目标,但我会保持简单,只回答你的问题。
在创建小部件的循环中,每次迭代都要重新分配变量。当循环结束时,变量,第一个示例中的'strength',只引用了最后创建的条目小部件。
一个简单的解决方案是将小部件放在列表中:

strength = []
for i in range(4):
    strength.append(Entry(STR))
    strength[i].grid(row=i, column=0, pady=5

然后在插入时:

strength[i].insert(0, value)

**编辑:**这里有一个简化/缩短代码的快速和肮脏的例子。总数假设你正在做4d 6,下降最低。

import random
import tkinter as tk
from tkinter import ttk

STAT_BLOCKS = ['STR', 'DEX', 'CON', 'WIS', 'INT', 'CHA']

fields = {}
buttons = {}
labels = {}

def roll_dice(num_sides, num_dice=1):
    return [random.randint(1, num_sides) for i in range(num_dice)]

def fill(stat, rolled_values):
    for idx, value in enumerate(rolled_values):
        fields[stat][idx].insert(0, value)
    buttons[stat].config(state='disabled')
    labels[stat].config(text=f'Total: {sum(sorted(rolled_values)[1:])}')

def reset():
    for stat in STAT_BLOCKS:
        for field in fields[stat]:
            field.delete(0, 'end')
        buttons[stat].config(state='normal')
        labels[stat].config(text='')

root = tk.Tk()

for stat in STAT_BLOCKS:
    frame = ttk.Labelframe(root, text=stat)
    frame.pack(side='left', padx=10)

    buttons[stat] = ttk.Button(
        frame,
        text='ROLL',
        command=lambda s=stat: fill(s, roll_dice(6, 4))
    )
    buttons[stat].pack(pady=5)

    fields[stat] = [ttk.Entry(frame, width=3, justify='right')
                    for i in range(4)]
    for field in fields[stat]:
        field.pack(pady=(0, 5))

    labels[stat] = ttk.Label(frame)
    labels[stat].pack(pady=(0, 5))

reset_button = ttk.Button(text='Reset', command=reset).pack(side='right', padx=(0, 10))

root.mainloop()

相关问题