【问题标题】:Accessing list of Buttons in python Tkinter [duplicate]访问python Tkinter中的按钮列表[重复]
【发布时间】:2016-10-29 00:08:46
【问题描述】:

以下是我的控制面板代码,上面有 8 个按钮。

from Tkinter import *
import ttk

class light_control(Frame):
  def __init__(self,i,parent,root,ltext,btext):
    Frame.__init__(self,parent)
    self.lc_Label = Label(self,text=ltext).pack()
    self.lc_Button = Button(self,
                text=btext,
                width=10,
                command=lambda i=i:root.toggle_button(i)
                ).pack()

class mi_control_panel(Frame):
 def __init__(self, master=Tk()):
    Frame.__init__(self, master)   
    self.master = master
    self.init_window()

 def init_window(self):
    self.grid()
    self.master.title("Control Panel")
    self.pack(fill=BOTH, expand=1)
    self.master.attributes('-zoomed', True)
    self.state = True
    self.master.attributes("-fullscreen", self.state)
    self.light_controls = []
    self.render_notebook()

 def toggle_button(self,x):
    print self.light_controls[x].lc_Button

 def render_notebook(self):
    n = ttk.Notebook(self)
    f1 = ttk.Frame(n)  
    text2 = Label(f1,text='Control Panel for Lights',relief='ridge')
    text2.grid(row=0,column=0,columnspan=4)
    for x in xrange(8):
      b = light_control(x,f1,self,"Light "+str(x),"OFF")
      self.light_controls.append(b)
    for i in xrange(1,3):
      for j in xrange(4):
        self.light_controls[4*i+j-4].grid(row=i,column=j,padx='80',pady='30')

    n.add(f1, text='Lights')
    n.grid(row=0,column=0,sticky='EW')

micp = mi_control_panel()
micp.tk.mainloop()  

我的问题是,当我单击一个按钮时,我得到的只是无。那就是调用了函数 toggle_button 但我无法访问 light_control 类的变量 lc_Button。我打算做的是创建一个附加到同一回调函数的按钮列表,该回调函数标识单击了哪个按钮并相应地执行操作。我可以在 toggle_button 函数中打印变量 x。它工作正常。高度赞赏任何指南。提前致谢。

【问题讨论】:

  • 你有没有试过用lambda i=i:root.toggle_button(i)这个代码lambda i:root.toggle_button(i)来代替?这就是我定义 lambda 函数的方式。
  • lambda i: root.toggle_button(i) 给出错误TypeError: <lambda>() takes exactly 1 argument (0 given)

标签: python list object tkinter


【解决方案1】:

你的问题是

elf.lc_Button = Button(...).pack()

它分配给pack()返回的变量值,它总是None

你需要

elf.lc_Button = Button(...)
elf.lc_Button.pack()

顺便说一句:你和Label有同样的错误

self.lc_Label = Label(...).pack()

所以如果你需要使用self.lc_Label 那么你需要

self.lc_Label = Label(...)
self.lc_Label.pack()

【讨论】:

  • 成功了。非常感谢你。很抱歉给你添麻烦了。而且我为忽略这么简单的事情感到尴尬。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多