2017-02-28 117 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

相關問題