【问题标题】:Tkinter widget creation using Python3 of Rasberry Pi. Create an array of checkbuttons在 Raspberry Pi 上使用 Python3 创建 Tkinter 小部件。创建一个检查按钮数组
【发布时间】:2014-04-15 18:58:14
【问题描述】:

我希望创建一个复选框数组并将它们作为某种数组引用。 这使得使用更短的块更容易编写代码。 理想的情况是这样的

for IOBit in range(8)
    self.GPIO_Array[IOBit] = tk.BooleanVar()
    tk.Checkbutton(self.MyFrame , variable = self.GPIO_Array[IOBit] )

之后,我将拥有一个由 8 个 boolean 变量组成的数组,称为 GPIO_Array[]。 然后我想使用访问这些,例如

self.GPIO_Array[Index].get()

关于如何解决这个问题的任何想法可能是一种允许循环而不是一大块半重复代码的不同方法?

【问题讨论】:

  • 问题是什么?是什么阻止您完全按照您的建议去做?
  • 问题是对于所有按下的按钮来说,IOBit 的值总是 7,这不是我想要的。

标签: python arrays checkbox tkinter raspberry-pi


【解决方案1】:

由于您没有显示实际代码,只是“类似于”您的实际代码,因此很难确定您做错了什么。这是一个我试图模仿你想要的东西的工作示例:

import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        self.MyFrame = tk.Frame(self)
        self.MyFrame.pack(side="top", fill="x")

        self.GPIO_Array = []
        for IOBit in range(8):
            self.GPIO_Array.append(tk.IntVar())
            w = tk.Checkbutton(self.MyFrame, variable=self.GPIO_Array[IOBit],
                               onvalue=1, offvalue=0, command=self.show)
            w.pack(side="left")

        self.label = tk.Label(self, text="", width=8)
        self.label.pack(side="top", fill="x")

        # show the current value when the GUI first starts
        self.show()

    def show(self):
        s = ""
        for IOBit in range(8):
            s += str(self.GPIO_Array[IOBit].get())
        self.label.configure(text=s)

if __name__ == "__main__":
    root = tk.Tk()
    app = Example(root)
    app.pack(fill="both", expand=True)
    root.mainloop()

【讨论】:

    猜你喜欢
    • 2020-07-12
    • 1970-01-01
    • 1970-01-01
    • 2015-02-06
    • 2020-12-10
    • 2013-07-09
    • 1970-01-01
    • 2016-02-08
    • 1970-01-01
    相关资源
    最近更新 更多