2017-04-02 22 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の値が保持されるようになりました。 第2に、メソッド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 (?私は感覚を得るが、あなたはhttp://www.tkdocs.com/tutorial/widgets.htmlで説明したように、Comboboxを使用する場合があります)

を見ます
関連する問題