[英]Make a dictionary using tkinter, GUI
我想使用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
然后在程序中继续使用该功能有什么建议吗? 我很感激。 谢谢
您即将实现您想要的。 需要进行一些修改。 首先,让我们从输入框entry_1
和entry_2
。 像您一样使用text variable
是一种很好的方法。 但是我没有看到它们的定义,所以它们是:
x = StringVar()
y = StringVar()
接下来,我们需要更改如何调用commando
函数以及通过它传递的参数。 虽然我想传递x
和y
值,但是我不能仅使用command=commando(x.get(), y.get())
,我需要按如下方式使用lambda
:
but = Button(root, text="Execute", bg="#333333", fg="white", command=lambda :commando(x.get(), y.get()))
现在,为什么我将值x
和y
传递为x.get()
和y.get()
? 为了从tkinter变量(例如x
和y
获取值,我们需要使用.get()
。
最后,让我们修复commando
功能。 您不能像使用fL
作为参数那样使用它。 这是因为在那里设置的任何参数都将变为该函数的私有变量,即使它出现在代码的其他位置。 换句话说,将函数定义为def commando(fL):
将防止在commando
中评估函数外部的fL
词典。 您如何解决这个问题? 使用不同的参数。 由于我们将x
和y
传递给函数,因此我们将它们用作参数名称。 这是我们的函数现在的外观:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.