2017-04-02 70 views
0

我有這個列表框作爲類的一部分:在標籤Python3 Tkinter的顯示列表框項目時,點擊

def myListbox(self): 
selection = Label(self, text="Please select Country").grid(row=0,column=0) 

countries = Listbox(self, width = 20, height = 75) 
countries.grid(row=0, column=1) 

# I have a function that populates the country names from 
# a text file and displays the names in the Listbox. 
# I want to be able to select a country from the Listbox 
# and have it displayed in a Label 

country_display = Label(self, text = "").grid(row = 0, column = 9) 
# this is where I'm not sure what code to use. 
# my code is 
countries.bind("<<ListboxSelect>>",country_display) 

目前什麼都不顯示。我在這裏錯過了什麼? 謝謝

回答

0

首先,當您在窗口小部件上執行方法grid時,它將返回None。這意味着您的變量現在保存值None,而不是對小部件的引用。 其次,方法bind將函數綁定到事件。此功能尚未被調用。但是,在您的bind中,您嘗試將Label(不是函數)分配給該事件;這根本不可能。 在下面的解決方案中,將爲該事件分配一個函數,該函數將檢索國家並設置標籤。

from tkinter import * 

countries_list = ["Netherlands", 
        "America", 
        "Sweden", 
        "England"] 

class MyClass(Tk): 
    def myListbox(self): 

     # better to structure it this way. The method grid simply returns None 
     # which meant that the variable hold None 
     # Now, the variable selection holds the widget 
     selection = Label(self, text="Please select Country") 
     selection.grid(row=0,column=0) 

     countries = Listbox(self, width = 20, height = len(countries_list)) 
     countries.grid(row=0, column=1) 
     for country in countries_list: 
      countries.insert(END, country) 

     country_display = Label(self, text = country, width = 15) 
     country_display.grid(row = 0, column = 9) 

     def get_country(*x): 
      # gets which country is selected, and changes 
      # the label accordingly 
      country = countries_list[countries.curselection()[0]] 
      country_display.config(text = country) 
     countries.bind("<<ListboxSelect>>", get_country) 

app = MyClass() 
app.myListbox() 

編輯:獲取更多信息Listbox看到http://effbot.org/tkinterbook/listbox.htm (雖然我的感覺,你可能想使用一個Combobox,如http://www.tkdocs.com/tutorial/widgets.html描述?)

相關問題