使用tkinter,GUI制作字典

时间:2015-12-12 03:22:45

标签: python dictionary input tkinter

我想通过使用GUI制作字典,我想要制作两个条目,一个用于对象,另一个用于键。我想创建一个执行信息的按钮并将其添加到空字典中。

from tkinter import *

fL = {}

def commando(fL):
    fL.update({x:int(y)})


root = Tk()
root.title("Spam Words")

label_1 = Label(root, text="Say a word: ", bg="#333333", fg="white")
label_2 = Label(root, text="Give it a value, 1-10:", bg="#333333", fg="white")
entry_1 = Entry(root, textvariable=x)
entry_2 = Entry(root, textvariable=y)

label_1.grid(row=1)
label_2.grid(row=3)

entry_1.grid(row=2, column=0)
entry_2.grid(row=4, column=0)

but = Button(root, text="Execute", bg="#333333", fg="white", command=commando)
but.grid(row=5, column=0)

root.mainloop()

我想在我的主程序中稍后使用该词典。你看它是不是一个函数,我会进入IDLE并做..

 def forbiddenOrd():

        fL = {}
        uppdate = True
        while uppdate:
            x = input('Object')
            y = input('Key')
            if x == 'Klar':
                break
            else:
                fL.update({x:int(y)})
        return fL

然后在我的程序中进一步使用该功能 有什么建议? 我很感激。谢谢

1 个答案:

答案 0 :(得分:1)

您即将实现自己想要的目标。需要进行一些修改。首先,让我们从输入框entry_1entry_2开始。像你一样使用text variable是一种很好的方法;但是我没有看到它们的定义,所以它们是:

x = StringVar()
y = StringVar()

接下来,我们需要更改您调用commando函数的方式以及您通过它传递的参数。我想传递xy值,但我不能通过使用command=commando(x.get(), y.get())这样的内容来实现,我需要使用lambda,如下所示:< / p>

but = Button(root, text="Execute", bg="#333333", fg="white", command=lambda :commando(x.get(), y.get()))

为什么我将值xy作为x.get()y.get()传递给我?为了从xy等tkinter变量中获取值,我们需要使用.get()

最后,让我们修复commando函数。您不能像使用fL作为参数那样使用它。这是因为您在那里设置的任何参数都成为该函数的私有变量,即使它出现在您的代码中的其他位置。换句话说,将函数定义为def commando(fL):将阻止在fL内评估函数外的commando字典。你是如何解决这个问题的?使用不同的参数。由于我们将xy传递给函数,因此我们将它们用作参数名称。这就是我们现在的功能:

def commando(x, y):
    fL.update({x:int(y)})

这将在您的词典中创建新项目。这是完成的代码:

from tkinter import *

fL = {}

def commando(x, y):
    fL.update({x:int(y)})  # Please note that these x and y vars are private to this function.  They are not the x and y vars as defined below.
    print(fL)

root = Tk()
root.title("Spam Words")

x = StringVar()  # Creating the variables that will get the user's input.
y = StringVar()

label_1 = Label(root, text="Say a word: ", bg="#333333", fg="white")
label_2 = Label(root, text="Give it a value, 1-10:", bg="#333333", fg="white")
entry_1 = Entry(root, textvariable=x)
entry_2 = Entry(root, textvariable=y)

label_1.grid(row=1)
label_2.grid(row=3)

entry_1.grid(row=2, column=0)
entry_2.grid(row=4, column=0)

but = Button(root, text="Execute", bg="#333333", fg="white", command=lambda :commando(x.get(), y.get()))  # Note the use of lambda and the x and y variables.
but.grid(row=5, column=0)

root.mainloop()
相关问题