有没有一种方法可以将字符串用作tkinter中输入框的变量名?

时间:2019-02-17 06:47:12

标签: python tkinter tkinter-entry

我正在尝试使用python / tkinter制作一个应用程序,该应用程序允许您为曲棍球队创建花名册。我想基于团队中球员的参数数量生成“ new_roster”框架,因此设法为每个球员创建了可变数量的输入框,但无法从所述输入框提取值。 / p>

在我当前的代码中,通过在空字符串中添加“ z”,根据用户希望其团队中的玩家数量生成列表。然后,下一个函数遍历列表,设置字符串= Entry(frame,xxx),我最初尝试使用int进行操作,但这似乎无关紧要。我也尝试过将str设为StringVar,但它也不起作用。

每次创建后,我都尝试引用输入框,例如

a = (player_list[0])
b = a.get

我收到以下错误:

错误:“ str”对象没有属性“ get”

很长一段时间:https://repl.it/@masoneischens/StableToughTheories

重要部分:

我非常费解的列表创建循环(entry2 =团队中的玩家数量)

  for i in range(int(entry2.get())):
    a = "z"
    for u in range(i):
        a += "z"
    player_list.insert(i - 1, a)

实际创建输入框的循环(pr =相应的行)     对于player_list中的n:

    pr += 1
    a= Entry(edit_roster, width = 15)
    a.grid(row = pr, column =3)

将值保存到csv文件的功能(fn =文件名,s =名称不带“ .csv”)

def save_new_file(s):
    global player_list
    fn = str(s) + ".csv"
    with open(fn, mode='w') as roster_file:
        roster_writer = csv.writer(roster_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
       for i in player_list:
            b = i.get()
            roster_writer.writerow([b, "player 1 "])

基本上,我需要能够使用字符串作为名称来创建和引用变量,或者通过某种方式将字符串转换为正确的变量名称,以便能够从使用所述字符串创建的输入框中提取值。

1 个答案:

答案 0 :(得分:0)

发生错误,因为您正在对字符串调用get()方法。 代替在get()上调用player_list方法,请执行以下操作:

  1. 创建一个entry_list

    global entry_list
    entry_list = []
    
  2. 将条目插入条目列表

    entry_list.append(a)
    
  3. get()中的条目调用entry_list方法

    global entry_list
    for i in entry_list:
        print(i.get())
    

这是您代码的更新版本。在这里,我只是打印了条目中的值:

from tkinter import *
from tkinter import messagebox
from tkinter import simpledialog
import csv
import random

sample = Tk()
sample.geometry("500x500")


# lists


# functions
def switch_newroster():
    new_roster.tkraise()


def switch_startpage():
    start_page.tkraise()


def switch_loadroster():
    load_roster.tkraise()


def get_file():
    if entry_getfile_act.get() == "":
        messagebox.showerror("ERROR!!", "Please enter a file name")
    else:
        print("good job")


def create():
    global player_list

    # ADD_1 Create new global entry_list #####
    global entry_list
    entry_list = []

    player_list = []
    number_list = []

    pos_list = []

    pr = 3
    nr = 3
    gr = 3
    posr = 3
    ar = 3
    gaar = 3
    if entry2.get() == "":
        messagebox.showerror("ERROR!!", "Enter number of players")
        return False
    elif entry1.get() == "":
        messagebox.showerror("ERROR!!", "Please enter a team name")
        return False
    elif int(entry2.get()) > 35 or int(entry2.get()) <= 0:
        messagebox.showerror("ERROR!!", "Roster can contain 1-35 players")
    else:
        o = "we coolin my dude"
    for i in range(int(entry2.get())):
        a = "z"
        for u in range(i):
            a += "z"
        player_list.insert(i - 1, a)
    for i in range(int(entry2.get())):
        a = i + 1
        number_list.insert(i - 1, a)
    for i in range(int(entry2.get())):
        a = i + 1
        pos_list.insert(i - 1, a)

    print(player_list)
    team_name = Label(edit_roster, text=entry1.get())
    team_name.grid(row=1, column=3)
    for n in player_list:
        pr += 1
        n = StringVar()
        a = Entry(edit_roster, width=15, textvariable=n)
        a.grid(row=pr, column=3)

        # ADD_2 Append entries to entry_list #####
        entry_list.append(a)

    for n in number_list:
        nr += 1
        n = Entry(edit_roster, width=2)
        n.grid(row=nr, column=1)
    for n in pos_list:
        posr += 1
        pos = StringVar(sample)
        pos.set(n + 1)
        n = OptionMenu(edit_roster, pos, "G", "LW", "RW", "D")
        n.grid(row=posr, column=5)
    edit_roster.tkraise()


def editstats():
    goal_list = []
    assist_list = []
    gaa_list = []
    player_list = []
    number_list = []
    pos_list = []

    pr = 3
    nr = 3
    gr = 3
    posr = 3
    ar = 3
    gaar = 3

    lbl5 = Label(edit_stats, text="G")
    lbl5.grid(row=3, column=6)

    lbl6 = Label(edit_stats, text="A")
    lbl6.grid(row=3, column=5)

    lbl7 = Label(edit_stats, text="GAA")
    lbl7.grid(row=3, column=5)
    for i in range(int(entry2.get())):
        a = i + 1
        goal_list.insert(i - 1, a)
    for i in range(int(entry2.get())):
        a = i + 1
        gaa_list.insert(i - 1, a)
    for i in range(int(entry2.get())):
        a = "z"
        for u in range(i + 1):
            a += "z"
            assist_list.insert(i - 1, a)
    for n in goal_list:
        gr += 1
        n = Entry(edit_roster, width=2)
        n.grid(row=gr, column=4)
    for n in assist_list:
        ar += 1
        n = Entry(edit_roster, width=2)
        n.grid(row=ar, column=2)
    for n in gaa_list:
        gaar += 1
        n = Entry(edit_roster, width=2)
        n.grid(row=gaar, column=1)
    edit_roster.tkraise()


def save_new_file(s):
    global player_list

    # ADD_3 Get values from entries of entry_list #####
    global entry_list
    for i in entry_list:
        print(i.get())

    # fn = str(s) + ".csv"
    # with open(fn, mode='w') as roster_file:
    #     roster_writer = csv.writer(roster_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    #     roster_writer.writerow(['John Smith', 'Accounting', 'November'])
    #     roster_writer.writerow(['Erica Meyers', 'IT', 'March'])
    #     for i in player_list:
    #         b = i.get()
    #         roster_writer.writerow([b, "player 1 "])


def get_filename():
    global player_list
    print()
    filename = simpledialog.askstring("input string", "What do you want to call your file?")
    print(filename)
    save_new_file(filename)


# frames
# start page
start_page = Frame(sample, bg="pink", height="50", width="60")
start_page.grid(row=0, column=0, sticky="nsew")
# new roster
new_roster = Frame(sample, bg="yellow")
new_roster.grid(row=0, column=0, sticky="nsew")
# editable roster
edit_roster = Frame(sample, bg="Blue")
edit_roster.grid(row=0, column=0, sticky="nsew")
# load roster
load_roster = Frame(sample)
load_roster.grid(row=0, column=0, sticky="nsew")
# edit stats
edit_stats = Frame(sample)
edit_stats.grid(row=0, column=0, sticky="nsew")
start_page.tkraise()

# buttons
# start page
new_roster_b = Button(start_page, command=switch_newroster, text="NEW ROSTER", height="2", width="10")
new_roster_b.grid(row=1, column=2)

load_roster_b = Button(start_page, command=switch_loadroster, text="LOAD ROSTER", height="2", width="10")
load_roster_b.grid(row=2, column=2)

# load roster
entry_getfile_b = Button(load_roster, text="Find", command=get_file)
entry_getfile_b.grid(row=2, column=3)

back_b = Button(load_roster, command=switch_startpage, text="Back")
back_b.grid(row=3, column=1)

# new roster
back_b = Button(new_roster, command=switch_startpage, text="Back")
back_b.grid(row=3, column=1)

create_b = Button(new_roster, command=create, text="Create Team")
create_b.grid(row=2, column=5)

# edit roster
save_b = Button(edit_roster, command=get_filename, text="Save")
save_b.grid(row=3, column=6)

# other widgets

# start page

# load roster
entry_lbl_getfile = Label(load_roster, text="Enter File NAME!!!")
entry_lbl_getfile.grid(row=2, column=1)

entry_getfile_act = Entry(load_roster)
entry_getfile_act.grid(row=2, column=2)

# new roster
lbl1 = Label(new_roster, text="Team Name:")
lbl1.grid(row=2, column=1)

lbl8 = Label(new_roster, text="Number of Players:")
lbl8.grid(row=2, column=3)

entry1 = Entry(new_roster)
entry1.grid(row=2, column=2)

entry2 = Entry(new_roster)
entry2.grid(row=2, column=4)

# edit roster
lbl2 = Label(edit_roster, text="#")
lbl2.grid(row=3, column=1)

lbl3 = Label(edit_roster, text="Name")
lbl3.grid(row=3, column=3)

lbl4 = Label(edit_roster, text="Pos.")
lbl4.grid(row=3, column=5)

sample.mainloop()