簡體   English   中英

使用tkinter,GUI制作字典

[英]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_1entry_2 像您一樣使用text variable是一種很好的方法。 但是我沒有看到它們的定義,所以它們是:

x = StringVar()
y = StringVar()

接下來,我們需要更改如何調用commando函數以及通過它傳遞的參數。 雖然我想傳遞xy值,但是我不能僅使用command=commando(x.get(), y.get()) ,我需要按如下方式使用lambda

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

現在,為什么我將值xy傳遞為x.get()y.get() 為了從tkinter變量(例如xy獲取值,我們需要使用.get()

最后,讓我們修復commando功能。 您不能像使用fL作為參數那樣使用它。 這是因為在那里設置的任何參數都將變為該函數的私有變量,即使它出現在代碼的其他位置。 換句話說,將函數定義為def commando(fL):將防止在commando中評估函數外部的fL詞典。 您如何解決這個問題? 使用不同的參數。 由於我們將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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM