在数组Python中创建tkinter中的按钮

时间:2016-05-26 22:34:11

标签: python arrays python-3.x button tkinter

我正在寻找的是如何通过迭代自动创建按钮网格。

例如我有这个数组

Array = 
       [[0,0,0,0,0,0,0], 
        [0,0,0,0,0,0,0], 
        [0,0,0,0,0,0,0], 
        [0,0,0,0,0,0,0], 
        [0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0]]

我看起来像

from tkinter import *

window = Tk ()
def create_buttons ():
    global Array
    for rows in Array:
       for numbers in rows:
           button = Button (text = 'Hello')
           button.pack () 
window.mainloop ()

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:2)

让我们加入MCVE @BryanOakley 建议您使用面向对象的概念。

在下面的代码中,initialize()方法创建一个6x7 numpy的零数组(与你的一样),然后遍历其2个轴(维度)以在每次迭代时创建一个按钮:

'''
Created on May 27, 2016

@author: Billal BEGUERADJ
'''

import Tkinter as Tk
import numpy as np

class Begueradj(Tk.Frame):
   def __init__(self,parent):
      Tk.Frame.__init__(self, parent)
      self.parent = parent
      self.initialize()

   def initialize(self):
      '''
      Draw the GUI
      '''
      self.parent.title("RUN ON START TEST")       
      self.parent.grid_rowconfigure(1,weight=1)
      self.parent.grid_columnconfigure(1,weight=1)

      self.frame = Tk.Frame(self.parent)  
      self.frame.pack(fill=Tk.X, padx=5, pady=5)

      # Create a 6x7 array of zeros as the one you used
      self.a = np.zeros((6,7))
      for i in range(0,self.a.shape[0]):
          for j in range(0,self.a.shape[1]):
               self.b = Tk.Button(self.frame, text = 'Hello')
               self.b.grid(row=i,  column= j)

# Start the main program here               
if __name__ == "__main__": 
   root=Tk.Tk()
   app = Begueradj(root)   
   root.mainloop()

以下是运行上述程序后的内容:

enter image description here