武易文 2020-09-23 14:09 采纳率: 100%
浏览 1063
已采纳

python中tkinter库中button如何通过command获取该button的名称

import tkinter
import webbrowser
def open_url(url):
    webbrowser.open(names['new_url%s' % t], new=0)
for t in range(0,5):
    names['new_url%s' % t]='http://www.cncotton.com/sy_59/gjmh_1401'
    names['x%s' % t] =tkinter.Button(root, text =new_d,relief="flat",command=lambda:open_url(names['new_url%s' % t]))
    names['x%s' % t].pack()
root.mainloop()

通过动态命名了5个button,然后,通过点击每个button,再进入相应的网页;但是,每次点击只会进入t=4时候的网页;我想到的解决办法是,command=函数,这个函数可以获取目前button的名称,然后通过名称再去匹配相应的url,不过如何才能获取到此时的button的名称呢

  • 写回答

2条回答 默认 最新

  • a569528788 2020-09-23 14:34
    关注

    在生成Button的时候传不同参数去函数
    例如

    self.button1 = Tkinter.Button(self, ..., command=lambda: self.OnButtonClick(1))
    ...
    self.button2 = Tkinter.Button(self, ..., command=lambda: self.OnButtonClick(2))
    

    函数

    def OnButtonClick(self, button_id):
        if button_id == 1:
            # self.button1 was clicked; do something
        elif button_id == 2:
            # self.button2 was clicked; do something
    

    给Button绑定事件

    from Tkinter import *
    
    def OnButtonClick(event):
        w = event.widget                      
        print w._name
    
    root = Tk()
    
    but_strings = ['But1', 'But2', 'But3']  
    buttons = [] 
    for label in but_strings:
        button_n = Button(root, text=label)
        button_n.pack()
        button_n.bind('<Button-1>', OnButtonClick)     # 绑定事件
    
        buttons.append(button_n)
    
    root.mainloop() 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog