【问题标题】:tkinter event binding to buttontkinter 事件绑定到按钮
【发布时间】:2013-08-15 15:08:08
【问题描述】:
from Tkinter import *

master = Tk()

def callback():
   print "click!"

b = Button(master, text="OK", command=callback)
b.pack()

mainloop()

现在在 iPython 中运行它会打印“点击!”到控制台。如果我希望脚本或函数的结果出现在 GUI 框中,在按钮下我该如何实现?盒子的大小需要提前分配吗?

编辑: 我要调用的函数其实比上面的回调要复杂。当我运行以下代码时,它不是打印 clusOne.head() 而是打印

<function centroid at 0x2cf3410> 

到输出框。我希望能够打印由此函数而不是指针地址产生的数据行。

master = Tk()


# The output box prints an address (pointer) as a result of running this function. 
#I would like to see the output in the box.

df=pd.read_csv('8162013.csv')
df=df.set_index('date1')

# Initialize the centroid.
cen1=df.mean()
v=ny.random.randn()+10
cen2=df.mean()-v
train=df[0:1615]


def centroid(train,cen1,cen2):

  for i in range(0,3):

    # Sum of squares. Results in a series containing 'date' and 'num' 
    sorted1=((train-cen1)**2).sum(1)
    sorted2=((train-cen2)**2).sum(1)

    # This makes a list of the cluster1 and cluster2
     a=[train.ix[i] for i in train.index if sorted1[i]<sorted2[i]]
     b=[train.ix[i] for i in train.index if sorted1[i]>=sorted2[i]]

     # Back to a dataframe...
    clusOne=pd.DataFrame(a,columns=['ES','US','GC'])
    clusTwo=pd.DataFrame(b,columns=['ES','US','GC'])

 # Update the centroid.
    cen1=clusOne.mean()
    cen2=clusTwo.mean()

     print clusOne.head()
     print "I'm computing your centroid."




def callback():
   listbox.insert(END, centroid)

  b = Button(master, text="Cluster", command=callback)
  listbox = Listbox(master)
   b.pack()
   listbox.pack()

   mainloop()

【问题讨论】:

    标签: python-2.7 tkinter pandas ipython


    【解决方案1】:

    您可以创建一个 tkinter 列表框,并在每次有人按下按钮时向其中添加文本:

    from Tkinter import *
    
    master = Tk()
    
    def callback():
       listbox.insert(END, "Click!")
    
    b = Button(master, text="OK", command=callback)
    listbox = Listbox(master)
    b.pack()
    listbox.pack()
    
    mainloop()
    

    【讨论】:

    • 谢谢,我需要查看结果的实际功能没有显示在输出框中。想法?
    • 当您说输出框时,您是指列表框吗?我很确定您的问题是您需要调用您的centroid 而不仅仅是引用它(不要忘记给它它的参数)。
    • 假设函数没有参数,我假设你的意思应该是command=callback()? (即括号)虽然查看“使用函数”部分,但在此示例中,它们没有将 callback() 传递给按钮函数中的命令。
    • 我的意思是在callback 函数中调用centroid 函数,而不是仅仅引用它。此外,让您的 centroid 函数返回您想要放入列表框中的内容。
    猜你喜欢
    • 1970-01-01
    • 2018-06-25
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-30
    相关资源
    最近更新 更多