2017-07-07 69 views
0

你好Python社區的顯示結果,如何存儲在一個空列表的字符串,並在列表框

使用Python 3.6和Im難倒了如何在一個空的列表中顯示存儲的項目添加到列表框上即時通訊。任何人都可以評估我的代碼並告訴我我錯過了什麼嗎?提前致謝!

from tkinter import * 

root = Tk() 
root.title("Name Entry") 
root.geometry("240x250") 

mylist = [] 

def get_data(l): 
    l.append(box1.get()) 
    print(l) 

label1 = Label(root,text = "ID:",height = 2) 
label1.grid(row = 0, column = 0) 

ID=StringVar() 
box1 = Entry(root, bd = 4, textvariable = ID) 
box1.grid(row = 0, column = 1) 

botonA = Button(root, text = "accept",command=lambda: get_data(mylist), width = 5) 
botonA.grid(row = 0, column = 2) 

list_names = Listbox(root).grid(row = 2, column = 1, rowspan = 7) 
for item in mylist: 
    list_names.insert("end", item) 

root.mainloop() 

從利瑪竇的幫助下,我能創造我想要的東西。再次感謝您爲我解決這個問題! :)

{from tkinter import * 

root = Tk() 
root.title("Name Entry") 
root.geometry("240x250") 

mylist = [] 

def get_data(l): 
    l.append(box1.get()) 
    print(l) 
    display_data() 

def display_data(): 
    list_names.delete(0, "end") 

    for items in mylist: 
     list_names.insert(END, items) 

label1 = Label(root,text = "ID:",height = 2) 
label1.grid(row = 0, column = 0) 

ID = StringVar() 
box1 = Entry(root, bd = 4, textvariable = ID) 
box1.grid(row = 0, column = 1) 

botonA = Button(root, text = "accept",command = lambda: get_data(mylist), 
width = 5) 
botonA.grid(row = 0, column = 2) 

list_names = Listbox(root) 
list_names.grid(row = 2, column = 1, rowspan = 7) 


root.mainloop()} 
+0

嗨,歡迎來到Stack Overflow,請抽出時間通過[Welcome tour](https://stackoverflow.com/tour)瞭解你在這裏的方式(也可以獲得你的第一個徽章),閱讀如何創建[Minimal,Complete和Verifiable示例](https://stackoverflow.com/help/mcve),並檢查[如何提出好問題](https://stackoverflow.com/help/)如何問),這樣你可以增加獲得反饋和有用答案的機會。 – DarkCygnus

+0

如何將一個項目存儲在一個空列表中?如果有存儲的東西,它不會是空的。 –

回答

2

您必須在按下按鈕時插入元素!在您的代碼中,當mylist爲空時,您將其添加到列表框中。

這裏是工作代碼:

from tkinter import * 

root = Tk() 
root.title("Name Entry") 
root.geometry("240x250") 

mylist = [] 


def get_data(l): 
    l.append(box1.get()) 
    list_names.insert(END, l) 
    print(l) 


label1 = Label(root, text="ID:", height=2) 
label1.grid(row=0, column=0) 

ID = StringVar() 
box1 = Entry(root, bd=4, textvariable=ID) 
box1.grid(row=0, column=1) 

botonA = Button(root, text="accept", command=lambda: get_data(mylist), width=5) 
botonA.grid(row=0, column=2) 

list_names = Listbox(root) 
list_names.grid(row=2, column=1, rowspan=7) 

root.mainloop() 

我還修改了其他兩件事情:

  • 我不知道這是否是你想要的,但l.append(box1.get ())將列表框中的所有元素添加到列表框中,而不僅僅是最後一個,因爲我認爲您需要。

  • list_names =列表框(根).grid(行= 2,列= 1,rowspan的= 7)list_names變量是網格函數的結果(這是無)。你必須首先保存列表框變量,並將其格子化。

+0

這就是問題 - 但是這樣做的工作?函數可以看到list_names嗎? – doctorlove

+0

是的,因爲* get_data *在創建列表框後運行。實際上可以用更好的方式編寫代碼,因爲調用全局變量(在本例中爲列表框變量)的函數並不是很好,因爲它尚未創建。 –

+0

夥計們!感謝您爲我清理!作爲Python新手,瞭解v2和v3之間的區別有點困難。 Matteo,使用您提供的數據我能夠創建我正在尋找的東西。我還添加了一個函數來清除列出的名稱,然後垂直顯示。 – Hellyeah

相關問題