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

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
    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() 
    
    点赞 评论
  • caozhy
    names['x%s' % t] =tkinter.Button(root, text =new_d,relief="flat",command=btn_click(names['x%s' % t]))
    
    
    def btn_click(b):
        open_url(b)
    
    点赞 评论

相关推荐