使用tkinter和listbox的Python无法获得提供答案的按钮

时间:2017-12-01 17:06:47

标签: python tkinter listbox

使用python 3.6,tkinter和mathplotlib。

创建了一个列表框,但我无法弄清楚如何让每个按钮返回不同的图形。

创建框

window.title( 'Employee Selection' )
frame = Frame( window )
listbox = Listbox( frame )
listbox.insert( 1 , '1')
listbox.insert( 2 , '2')
listbox.insert( 3, '3')
listbox.insert( 4, '4')
listbox.pack()

我用这个

listbox.bind('<<ListboxSelect>>', immediately)
print(listbox.get(ACTIVE))

如果单击box 1它选择运行一件事,我该怎么做呢? 并且box 2它选择运行另一个......

这是整件事

import matplotlib.pyplot as plt

from tkinter import *

import tkinter.messagebox as box



# data to plot

n_groups = 4

scores_1 = (10,8,6,7)

scores_4 = (7,6,6,7)

scores_2 = (9,9,8,10)

scores_3 = (6,5,7,5)



def immediately(e):

    # create plot

        fig, ax = plt.subplots()

         index = np.arange(n_groups)

        bar_width = 0.35

        opacity = 0.8


    rects1 = plt.bar(index, 1, bar_width,

                     alpha=opacity,

                     color='b',

                     label='Joe')

        plt.xlabel('Person')

        plt.ylabel('Rating')

        plt.title('Performance Ratings')

        plt.xticks(index + bar_width, ('Q1', 'Q2', 'Q3', 'Q4'))

        plt.legend()



        plt.tight_layout()

        plt.show()





window = Tk()

window.title( 'Employee Selection' )

frame = Frame( window )

listbox = Listbox( frame )

    listbox.insert( 1 , '1')

    listbox.insert( 2 , '2')

    listbox.insert( 3, '3')

    listbox.insert( 4, '4')

    listbox.pack()

btn = Button( frame , text = 'Select')

btn.pack( side = RIGHT , padx = 5)

listbox.pack( side = LEFT )

frame.pack( padx = 70 , pady = 30 )



listbox.bind('<<ListboxSelect>>', immediately)
print(listbox.get(ACTIVE))
mainloop()

按钮1是硬编码的,因为我无法弄清楚如何选择其他

1 个答案:

答案 0 :(得分:0)

您必须在与<<ListboxSelect>>

绑定的函数内获取值
import tkinter as tk

# --- function ---

def on_selection(event):
    # here you can get selected element
    print('previous:', listbox.get('active'))
    print(' current:', listbox.get(listbox.curselection()))

    # or using `event`

    #print('event:', event)
    #print('widget:', event.widget)
    print('(event) previous:', event.widget.get('active'))
    print('(event)  current:', event.widget.get(event.widget.curselection()))

    print('---')

# --- main ---

root = tk.Tk()

listbox = tk.Listbox(root)
listbox.pack()

listbox.insert(1, 'Hello 1')
listbox.insert(2, 'Hello 2')
listbox.insert(3, 'Hello 3')
listbox.insert(4, 'Hello 4')

listbox.bind('<<ListboxSelect>>', on_selection)

root.mainloop()