Python 3.x 单击时,Python3 Tkinter会在标签中显示列表框项目

Python 3.x 单击时,Python3 Tkinter会在标签中显示列表框项目,python-3.x,tkinter,listbox,Python 3.x,Tkinter,Listbox,我将此列表框作为类的一部分: 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 f

我将此列表框作为类的一部分:

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)
目前什么也没有显示。我错过了什么?
首先,当您在小部件上执行方法网格时,它将不返回任何值。这意味着您的变量现在保存值None,而不是对小部件的引用。 其次,方法bind将函数绑定到事件。此函数尚无法调用。但是,在绑定中,您尝试将不是函数的标签分配给事件;这根本不可能。 在下面的解决方案中,为事件分配了一个函数,该函数检索国家并设置标签

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()
编辑:有关列表框的更多信息,请参阅 尽管我觉得您可能需要使用组合框,如中所述