2017-02-28 123 views
0

我想创建一个循环中的按钮的简单表,但我的代码不起作用。没有错误,但我看不到执行结果。我怎么能创建一个循环中的按钮

import sys 
from PyQt4 import QtGui, QtCore 

names = ['X+', 'X-', 'Y+',\ 
     'Y-', 'Z+', 'Z-',\ 
     'A1+', 'A1-', 'A2+',\ 
     'A2-', 'A3+', 'A3-',\ 
     'Hand'] 

pos = [(50, 100), (200, 100), (50, 200),\ 
     (200,200), (50, 300), (200,300),\ 
     (370, 100), (520, 100), (370, 200),\ 
     (520, 200), (370, 300), (520, 300),\ 
     (50, 400)] 

size = [(74, 74), (74, 74), (74, 74),\ 
     (74, 74), (74, 74), (74, 74),\ 
     (74, 74), (74, 74), (74, 74),\ 
     (74, 74), (74, 74), (74, 74),\ 
     (226, 74)] 

class Window(QtGui.QMainWindow): 

    ........... 

    def createButtons(self): 
     index = 0 
     self.buttons = [] 

     for i in names: 
      self.buttons.append(index) 
      self.buttons[index] = QtGui.QPushButton(self) 
      self.buttons[index].setText(i) 
      self.buttons[index].setGeometry(pos[index][0], pos[index][1], size[index][0], size[index][1]) 
      index += 1 

def runApp(): 
    app = QtGui.QApplication(sys.argv) 
    gui = Window() 
    gui.createButtons() 
    gui.show() 
    sys.exit(app.exec_()) 

runApp() 

你能帮我吗? 名称 - 名称列表, pos - 位置列表[x,y], 大小 - w和h的列表。

+0

什么是'namesVal',它在哪里声明?另外你似乎没有在for循环中使用'i'。 –

+0

对不起,我已更改列表的名称。 names = namesVal和self.buttons [index] .setText(i) – DWilde

回答

1

您只需要更改大小,以便您可以看到按钮。您必须使用resize()

import sys 
from PyQt4 import QtGui, QtCore 

names = ['X+', 'X-', 'Y+',\ 
     'Y-', 'Z+', 'Z-',\ 
     'A1+', 'A1-', 'A2+',\ 
     'A2-', 'A3+', 'A3-',\ 
     'Hand'] 

pos = [(50, 100), (200, 100), (50, 200),\ 
     (200,200), (50, 300), (200,300),\ 
     (370, 100), (520, 100), (370, 200),\ 
     (520, 200), (370, 300), (520, 300),\ 
     (50, 400)] 

size = [(74, 74), (74, 74), (74, 74),\ 
     (74, 74), (74, 74), (74, 74),\ 
     (74, 74), (74, 74), (74, 74),\ 
     (74, 74), (74, 74), (74, 74),\ 
     (226, 74)] 

class Window(QtGui.QMainWindow): 
    def __init__(self, parent=None): 
     super(Window, self).__init__(parent=parent) 

    def createButtons(self): 
     index = 0 
     self.buttons = [] 

     for i in names: 
      self.buttons.append(index) 
      self.buttons[index] = QtGui.QPushButton(self) 
      self.buttons[index].setText(i) 
      self.buttons[index].setGeometry(pos[index][0], pos[index][1], size[index][0], size[index][1]) 
      index += 1 

     self.resize(650, 500) 

def runApp(): 
    app = QtGui.QApplication(sys.argv) 
    gui = Window() 
    gui.createButtons() 
    gui.show() 
    sys.exit(app.exec_()) 

runApp() 

截图:

enter image description here

+0

非常感谢:) – DWilde

相关问题