2015-12-12 36 views
1

我想通過使用GUI製作字典,我想製作兩個條目,一個用於對象,另一個用於鍵。我想製作一個執行信息並將其添加到空字典的按鈕。使用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

你已經接近實現你想要的。需要進行一些修改。首先,讓我們從輸入框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())) 

現在我爲什麼值傳遞xyx.get()y.get()?爲了得到tkinter變量的值,如xy,我們需要使用.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() 
+0

我明白了! Camon,非常感謝你!然而,在我們關閉此頁面之前,我有一個問題。你爲什麼放lambda?它有什麼特別之處?我的意思是我在YouTube上觀看過一些視頻,但爲什麼我們在這種情況下使用它?我們已經定義了一個函數,但是我們仍然使用lambda? –

+0

@MajdJamal如果您需要將參數傳遞給函數,在tkinter應用程序(和其他GUI工具)中使用'lambda'特別有用。如果你使用了類似'command = function(param1,param2)'的東西,一旦應用程序啓動,該命令立即運行(儘管沒有用戶按下按鈕)。在'command ='中使用'lambda',當按下按鈕時,函數只能運行給定的參數。我建議你嘗試刪除lambda,看看會發生什麼。希望能夠澄清一些事情。 – Camon