Ejemplo n.º 1
1
    def addLCDNumbers(self):
        fortLCD = QLCDNumber(1, self)
        fortLCD.setFrameShape(QFrame.NoFrame)
        fortLCD.move(125, 50)
        fortLCD.resize(40, 40)
        fortLCD.display(self.square.ter.buildings.fort_lvl)
        incomeLCD = QLCDNumber(2, self)
        incomeLCD.setFrameShape(QFrame.NoFrame)
        incomeLCD.move(117, 10)
        incomeLCD.resize(40, 40)
        incomeLCD.display(self.square.ter.get_income())
        marketLCD = QLCDNumber(1, self)
        marketLCD.setFrameShape(QFrame.NoFrame)
        marketLCD.move(125, 90)
        marketLCD.resize(40, 40)
        marketLCD.display(self.square.ter.buildings.market_lvl)

        self.square.incomeChanged.connect(incomeLCD.display)
        self.square.fortUpgr.connect(fortLCD.display)
        self.square.marketUpgr.connect(marketLCD.display)
Ejemplo n.º 2
0
    def __init__(self, parent=None):
        super(LdcSettingsWindow, self).__init__(parent)

        label_current_limit_info = QLabel("Laser current limit in mA", self)
        label_current_limit_info.move(80, 15)

        display_current_limit = QLCDNumber(self)
        display_current_limit.move(50, 40)
        display_current_limit.resize(180, 50)

        self.slider_to_change_current_limit = QSlider(Qt.Horizontal, self)
        self.slider_to_change_current_limit.move(250, 60)
        self.slider_to_change_current_limit.setMaximum(200)
        self.slider_to_change_current_limit.valueChanged.connect(
            display_current_limit.display)

        button_to_set_current_limit = QPushButton(self)
        button_to_set_current_limit.setText("Set current limit")
        button_to_set_current_limit.move(380, 40)
        button_to_set_current_limit.resize(150, 50)
        button_to_set_current_limit.clicked.connect(self.set_current_limit)

        try:
            display_current_limit.display(
                MeasureDeviceConnect.ldc.get_current_limit_in_amper() * 1000)
        except Exception:
            pass

        self.setGeometry(600, 600, 600, 600)
        self.setWindowTitle('Ldc settings')
class DigitalClock(QMainWindow):

    def __init__(self):
        QMainWindow.__init__(self)
        self.initUI()

    def initUI(self):
        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.Time)
        self.timer.start(10)

        self.clock_screen = QLCDNumber(self)
        self.clock_screen.resize(250,100)

        # Added self.lcd.move and moved the clock 30px down to make space for buttons
        self.clock_screen.move(0,30)
        self.clock_screen.display(strftime("%H" + ":" + "%M"))


        self.r1 = QRadioButton("Hide seconds", self)
        self.r1.move(10, 0)
        self.r2 = QRadioButton("Show seconds", self)
        self.r2.move(110, 0)

        self.r1.toggled.connect(self.woSecs)
        self.r2.toggled.connect(self.wSecs)

        # ---------Window settings --------------------------------

        # Expanded window height by 30px

        self.setGeometry(300, 300, 250, 130)
        self.setWindowTitle("Digital Clock")
        self.setWindowIcon(QtGui.QIcon(""))
        self.show()

    # -------- Slots ------------------------------------------

    def Time(self):
        global var
        if var == True:
            self.clock_screen.display(strftime("%H" + ":" + "%M"))
        elif var == False:
            self.clock_screen.display(strftime("%H" + ":" + "%M" + ":" + "%S"))

    def wSecs(self):
        global var
        var = False

        self.resize(375, 130)
        self.clock_screen.resize(375, 100)
        self.clock_screen.setDigitCount(8)

    def woSecs(self):
        global var
        var = True

        self.resize(250, 130)
        self.clock_screen.resize(250, 100)
        self.clock_screen.setDigitCount(5)
Ejemplo n.º 4
0
 def addNumbers(self):
     cavNum = QLCDNumber(2, self)
     self.cavSld.valueChanged.connect(cavNum.display)
     self.cavSld.setValue(99)
     cavNum.resize(60, 40)
     cavNum.move(150, 60)
     infNum = QLCDNumber(2, self)
     self.infSld.valueChanged.connect(infNum.display)
     self.infSld.setValue(99)
     infNum.resize(60, 40)
     infNum.move(0, 60)
Ejemplo n.º 5
0
 def addGoldInfo(self, font):
     '''
     Adds gold LCDNumber and connects it with the correct signal.
     '''
     goldLbl = QLabel('Gold:', self)
     goldLbl.move(300, 10)
     goldLbl.setFont(font)
     goldLcd = QLCDNumber(4, self)
     goldLcd.move(360, 0)
     goldLcd.setFrameShape(QFrame.NoFrame)
     goldLcd.resize(65, 40)
     self.sig.goldChanged.connect(goldLcd.display)
     self.sig.goldChanged.emit(self.game.player.gold)
Ejemplo n.º 6
0
 def addIncomeInfo(self, font):
     '''
     Adds the income LCDNumber and connects it with the correct signals.
     '''
     incomeLbl = QLabel("Income:", self)
     incomeLbl.setFont(font)
     incomeLbl.move(460, 10)
     incomeLcd = QLCDNumber(3, self)
     incomeLcd.move(530, 0)
     incomeLcd.setFrameShape(QFrame.NoFrame)
     incomeLcd.resize(60, 40)
     self.sig.incomeChanged.connect(incomeLcd.display)
     self.sig.incomeChanged.emit(self.game.player.income())
Ejemplo n.º 7
0
class Main(QWidget):
    def __init__(self):
        super(Main, self).__init__()
        self.initUI()

    def initUI(self):

        timer = QTimer(self)
        timer.timeout.connect(self.Time)
        timer.start(10)

        self.lcd = QLCDNumber(self)
        self.lcd.resize(250, 100)

        self.lcd.move(0, 30)
        self.lcd.display(strftime('%H' + ':' + '%M'))

        self.r1 = QRadioButton('Hide seconds', self)
        self.r1.move(10, 0)
        self.r2 = QRadioButton('Show seconds', self)
        self.r2.move(110, 0)

        self.r1.toggled.connect(self.woSecs)
        self.r2.toggled.connect(self.wSecs)

        self.setGeometry(300, 300, 250, 130)
        self.setWindowTitle('Clock')
        self.setWindowIcon(QIcon(''))
        self.show()

    def Time(self):
        global var
        if var == True:
            self.lcd.display(strftime('%H' + ':' + '%M'))
        elif var == False:
            self.lcd.display(strftime('%H' + ':' + '%M' + ':' + '%S'))

    def wSecs(self):
        global var
        var = False

        self.resize(375, 130)
        self.lcd.resize(375, 100)
        self.lcd.setDigitCount(8)

    def woSecs(self):
        global var
        var = True
        self.resize(250, 130)
        self.lcd.resize(250, 100)
        self.lcd.setDigitCount(5)
Ejemplo n.º 8
0
 def addMaintInfo(self, font):
     '''
     Adds maintenance QLCDNumber and connects it with the correct signals.
     '''
     maintLbl = QLabel("Total maintenance:", self)
     maintLbl.move(620, 10)
     maintLbl.setFont(font)
     maintLcd = QLCDNumber(3, self)
     maintLcd.move(840, 7)
     maintLcd.setFrameShape(QFrame.NoFrame)
     maintLcd.resize(50, 30)
     self.sig.maintChanged.connect(maintLcd.display)
     maint = self.game.player.get_armies_maint()
     self.sig.maintChanged.emit(maint[0] + maint[1])
Ejemplo n.º 9
0
Archivo: egr.py Proyecto: pepilica/omaa
class Calculator(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(0, 0, 500, 500)

        self.btn = QPushButton('Расчитать', self)
        self.btn.resize(self.btn.sizeHint())
        self.btn.move(225, 125)
        self.btn.clicked.connect(self.Count)

        self.ln1 = QLineEdit(self)
        self.ln1.move(100, 100)
        self.ln2 = QLineEdit(self)
        self.ln2.move(300, 100)

        self.sum = QLCDNumber(self)
        self.sum.move(100, 400)
        self.dif = QLCDNumber(self)
        self.dif.move(200, 400)
        self.div = QLCDNumber(self)
        self.div.move(300, 400)
        self.mul = QLCDNumber(self)
        self.mul.move(400, 400)

    def Count(self):
        self.sum.display(int(self.ln1.text()) + int(self.ln2.text()))
        self.dif.display(int(self.ln1.text()) - int(self.ln2.text()))
        if int(self.ln2.text()) != 0:
            self.div.display(int(self.ln1.text()) / int(self.ln2.text()))
        else:
            self.div.display('error')
        self.mul.display(int(self.ln1.text()) * int(self.ln2.text()))
Ejemplo n.º 10
0
class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(300, 300, 300, 300)
        self.setWindowTitle('Первая программа')

        self.btn = QPushButton('Пуск', self)
        self.btn.move(120, 60)
        self.btn.clicked.connect(self.run)

        self.first_input = QLineEdit(self)
        self.first_input.move(20, 20)

        self.second_input = QLineEdit(self)
        self.second_input.move(160, 20)

        self.summa = QLabel(self)
        self.summa.setText("Сумма")
        self.summa.move(20, 100)

        self.summ = QLCDNumber(self)
        self.summ.move(200, 100)

        self.raznost = QLabel(self)
        self.raznost.setText("Разность")
        self.raznost.move(20, 140)

        self.ras = QLCDNumber(self)
        self.ras.move(200, 140)

        self.chastnoe = QLabel(self)
        self.chastnoe.setText("Частное")
        self.chastnoe.move(20, 180)

        self.chas = QLCDNumber(self)
        self.chas.move(200, 180)

        self.proisvedenie = QLabel(self)
        self.proisvedenie.setText("Произведение")
        self.proisvedenie.move(20, 220)

        self.prois = QLCDNumber(self)
        self.prois.move(200, 220)

    def run(self):
        try:
            x, y = list(map(int, [self.first_input.text(), self.second_input.text()]))
            self.summ.display(x + y)
            self.ras.display(x - y)
            try:
                self.chas.display(x / y)
            except:
                self.chas.display("ERROR")
            self.prois.display(x * y)
        except:
            pass
Ejemplo n.º 11
0
class Soc(QWidget):
    def __init__(self, parent):

        super(Soc, self).__init__(parent)

        self.arguments = Arg_Class()

        self.socValue = 0.0

        self.socLCD = QLCDNumber(self)
        self.socLCD.display(
            str(int(self.socValue)).zfill(4) + '.' +
            str((self.socValue - int(self.socValue)) * 10).zfill(4))
        self.socLCD.setFrameShape(QFrame.NoFrame)
        self.socLCD.setSegmentStyle(QLCDNumber.Flat)
        #self.socLCD.move(30,100)
        self.socLCD.move(0, 20)
        self.socLCD.resize(70, 80)

        self.socLabel = QLabel(self)
        self.socLabel.setText("soc: ")
        self.socLabel.move(10, 10)
        self.socLCD.show()
        self.socLabel.show()

    @pyqtSlot(float)
    def soc_update(self, value):
        if value < 0:
            value = 0
        self.socLCD.display(value)
        self.socValue = value
        self.update()
        #self.socGauge.display(str(int(self.socValue)).zfill(2)+'.'+ str((self.socValue - int(self.socValue))*10).zfill(2))

    def paintEvent(self, event):
        qp = QPainter(self)
        qp.setPen(Qt.white)

        qp.drawRect(70, 20, 70, 180)
        qp.drawRect(96, 10, 20, 10)
        if self.socValue < 0:
            self.socValue = 0
        if self.socValue < 20:
            qp.setBrush(Qt.red)
        else:
            qp.setBrush(Qt.green)

        qp.drawRect(70, 20 + (180 * (1 - (self.socValue / 100))), 70,
                    ((180 * self.socValue / 100)))
Ejemplo n.º 12
0
class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.s = 0

    def initUI(self):
        self.setGeometry(375, 200, 375, 200)
        self.setWindowTitle('Фокус со словами')

        self.btn = QPushButton('->', self)
        self.btn.resize(self.btn.sizeHint())
        self.btn.move(150, 80)
        self.btn.clicked.connect(self.count)

        self.label = QLabel(self)
        # Текст задается также, как и для кнопки
        self.label.setText("Первое число(целое):")
        self.label.move(20, 25)

        self.name_input = QLineEdit(self)
        self.name_input.move(20, 40)

        self.label2 = QLabel(self)
        # Текст задается также, как и для кнопки
        self.label2.setText("Второе число(целое):")
        self.label2.move(20, 105)

        self.name_input2 = QLineEdit(self)
        self.name_input2.move(20, 120)

        self.LCD_count = QLCDNumber(self)
        self.LCD_count.move(275, 25)
        self.LCD_count.display(0)

        self.LCD_count1 = QLCDNumber(self)
        self.LCD_count1.move(275, 65)
        self.LCD_count1.display(0)

        self.LCD_count2 = QLCDNumber(self)
        self.LCD_count2.move(275, 105)
        self.LCD_count2.display(0)

        self.LCD_count3 = QLCDNumber(self)
        self.LCD_count3.move(275, 145)
        self.LCD_count3.display(0)



    def count(self):
        a = int(self.name_input.text())
        b = int(self.name_input2.text())
        self.LCD_count.display(a + b)
        self.LCD_count1.display(a - b)
        self.LCD_count2.display(a * b)
        if b != 0:
            self.LCD_count3.display(a / b)
        else:
            self.LCD_count3.display('Error')
Ejemplo n.º 13
0
class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(300, 300, 300, 300)
        self.setWindowTitle('Миникалькулятор')

        self.btn = QPushButton('Рассчитать', self)
        self.btn.resize(self.btn.sizeHint())
        self.btn.move(100, 200)
        self.btn.clicked.connect(self.hello)

        self.label = QLabel(self)
        self.label.setText("Введите 1 число")
        self.label.move(10, 30)

        self.label = QLabel(self)
        self.label.setText("Введите 2 число")
        self.label.move(10, 60)

        self.chislo_input = QLineEdit(self)
        self.chislo_input.move(130, 30)

        self.chislo2_input = QLineEdit(self)
        self.chislo2_input.move(130, 60)

        self.LCD_plus = QLCDNumber(self)
        self.LCD_plus.move(10, 100)

        self.LCD_minus = QLCDNumber(self)
        self.LCD_minus.move(80, 100)

        self.LCD_delen = QLCDNumber(self)
        self.LCD_delen.move(150, 100)

        self.LCD_umn = QLCDNumber(self)
        self.LCD_umn.move(210, 100)

        self.label_error = QLabel(self)
        self.label_error.setText("")
        self.label_error.move(30, 140)
        self.label_error.resize(270, 20)

    def hello(self):
        chislo = float(self.chislo_input.text())
        chislo2 = float(self.chislo2_input.text())
        print(chislo)
        if chislo2 == 0:
            self.label_error.setText("На 0 делить нельзя. Измените 2 число.")
        else:
            self.LCD_delen.display(chislo // chislo2)
        self.LCD_plus.display(chislo + chislo2)
        self.LCD_minus.display(chislo - chislo2)
        self.LCD_umn.display(chislo * chislo2)
Ejemplo n.º 14
0
class WinForm(QWidget):
    def __init__(self, parent=None):
        super(WinForm, self).__init__(parent)
        self.setGeometry(300, 300, 350, 350)
        self.setWindowTitle('Sentiment Analysis')
        self.Run = QPushButton('Run', self)
        self.Run.setGeometry(250, 100, 80, 40)
        self.Run.setStyleSheet("background-color: green")
        self.Run.clicked.connect(self.run)

        self.Inf = QLabel(self)
        self.Inf.move(40, 40)
        self.Inf.resize(200, 40)
        self.Inf.setText('Please type in something')

        self.Inline = QLineEdit(self)
        self.Inline.move(40, 100)
        self.Inline.resize(200, 40)

        self.Outline = QLCDNumber(self)
        self.Outline.move(90, 170)
        self.Outline.resize(150, 80)
        self.Outline.setDigitCount(2)
        self.Outline.display(00)

        self.Run.setDisabled(True)
        self.Inline.textChanged.connect(self.disableRun)

    def disableRun(self):

        self.Run.setDisabled(True)

        for ele in self.Inline.text():
            if ele != ' ':
                self.Run.setDisabled(False)

    def run(self):

        self.Inf.setText('Please waiting........')
        time.sleep(0.5)
        score = analyze(self.Inline.text())
        self.Outline.display(score)
        self.Inf.setText('Please type in something')
Ejemplo n.º 15
0
class Channel3(QWidget):
    def __init__(self, parent, name, x, y, value):
        super(Channel3, self).__init__(parent)

        self.label = QLabel(name, self)
        self.label.resize(CHANNEL_WIDTH, 20)
        self.label.move(x, y)

        self.gauge = QLCDNumber(self)
        self.gauge.display(value)
        self.gauge.move(x, y + 20)
        self.gauge.resize(CHANNEL_WIDTH, CHANNEL_HEIGHT)
        self.gauge.setFrameShape(QFrame.NoFrame)
        self.gauge.setSegmentStyle(QLCDNumber.Flat)

    @pyqtSlot(float)
    def channel_update(self, value):
        self.gauge.display(value)
        self.value = value
        self.update()
Ejemplo n.º 16
0
    def __init__(self):
        super().__init__()
        self.setAcceptDrops(True)
        self.game = Game(4)  # Make game with 4 players

        self.sig = Signals()
        endTurnButton = QPushButton("&EndTurn", self)
        endTurnButton.clicked.connect(self.endTurn)
        endTurnButton.move(1260, 720)
        turnLcd = QLCDNumber(3, self)
        turnLcd.move(90, 715)
        turnLcd.setSegmentStyle(QLCDNumber.Filled)
        turnLcd.resize(60, 40)
        turnTxt = QLabel("Turn:", self)
        turnFont = QFont()
        turnFont.setPointSize(20)
        turnTxt.setFont(turnFont)
        turnTxt.move(20, 720)

        self.sig.turnChanged.connect(turnLcd.display)
        self.sig.turnChanged.emit(self.game.turn)

        quitB = QPushButton("&Quit", self)
        quitB.clicked.connect(self.quit)
        quitB.move(1150, 720)

        self.showPlayerInfo()

        self.coords = []
        self.setWindowTitle("Territory War")
        n = self.game.map.dim
        self.makeMap(1100 // n, 600 // n, n)
        self.setWindowState(Qt.WindowFullScreen)
        self.setFixedSize(self.size())

        self.showArmies()
        self.addDiplomacyLabels()

        thread = threading.Thread(target=self.game.start, args=(0, ))
        thread.start()
Ejemplo n.º 17
0
class MainWindow(Ui_MainWindow, QMainWindow):
    """
    主界面二次设计
    """
    def __init__(self):
        super(MainWindow, self).__init__()

        # 获取桌面尺寸
        desktop = QApplication.desktop()
        desk_width = desktop.screenGeometry().width()
        desk_height = desktop.screenGeometry().height()

        # 摄像头图像设置
        self.frame = DIYLabel(self)
        self.frame.setGeometry(0, 0, desk_width, desk_height)

        self.setupUi(self)

        # 按钮定位
        self.buttons = [
            self.att_rec, self.face_login, self.face_rec, self.face_reg
        ]
        map(
            lambda x: x.move(
                desk_width * 0.80, desk_height * 0.33 + self.buttons.index(x) *
                (x.height() + 8)), self.buttons)
        map(lambda x: x.raise_(), self.buttons)

        # 设置时钟
        self.clock = QLCDNumber(self)
        self.clock.setDigitCount(10)
        self.clock.setMode(QLCDNumber.Dec)
        self.clock.setSegmentStyle(QLCDNumber.Flat)
        self.clock.display(time.strftime("%X", time.localtime()))
        self.clock.setStyleSheet("QLCDNumber{color:rgba(255,0,0,100);}")
        self.clock.resize(280, 120)
        self.clock.move(50, desk_height - 30 - self.clock.height())

        self.setWindowFlags(Qt.FramelessWindowHint)  # 隐藏窗口
        self.showFullScreen()  # 窗体全屏
Ejemplo n.º 18
0
class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.x = choice(range(10))
        self.y = choice(range(10))
        self.z = choice(range(10))
        self.steps = 10

    def initUI(self):
        self.setGeometry(300, 300, 300, 300)
        self.setWindowTitle('Числовая игра')

        self.plus = QPushButton('+' + str(self.y), self)
        self.plus.resize(self.plus.sizeHint())
        self.plus.move(170, 150)
        self.plus.clicked.connect(self.P)

        self.minus = QPushButton('-' + str(self.z), self)
        self.minus.resize(self.minus.sizeHint())
        self.minus.move(20, 150)
        self.minus.clicked.connect(self.M)

        self.label = QLabel(self)
        self.label.setText(str(self.x))
        self.label.move(80, 30)

        self.LCD_count = QLCDNumber(self.x, self)
        self.LCD_count.move(110, 80)

        self.count = 0

    def P(self):
        self.x += self.y
        self.steps -= 1

    def M(self):
        self.x -= self.z
        self.steps -= 1
Ejemplo n.º 19
0
class FreeWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.makeUI()

    def makeUI(self):
        self.setGeometry(0, 0, 420, 300)
        self.setWindowTitle(
            "i hate pep8 6.0, added input-box(pay-respect counter)")

        self.frstbtn = QPushButton("F", self)
        self.frstbtn.resize(125, 100)
        self.frstbtn.move(137, 100)
        self.frstbtn.clicked.connect(self.i61)

        self.text = QLabel(self)
        self.text.setText("You have already PAYED RESPECT ")
        self.text.move(10, 225)

        self.counter = QLCDNumber(self)
        self.counter.move(200, 225)

        self.text = QLabel(self)
        self.text.setText("- these amount of times ")
        self.text.move(270, 225)

        self.text_for_input = QLabel(self)
        self.text_for_input.setText("Insert here ur int step ->")
        self.text_for_input.move(10, 50)

        self.inputbox = QLineEdit(self)
        self.inputbox.move(200, 50)

        self.count = 0

    def i61(self):
        self.count += int(self.inputbox.text())
        self.counter.display(self.count)
Ejemplo n.º 20
0
    def initUI(self):
        self.setGeometry(0, 0, 500, 300)
        self.setWindowTitle('Фокус со словами')

        self.btn = QPushButton('->', self)
        self.btn.resize(50, 50)
        self.btn.move(225, 125)
        self.btn.clicked.connect(self.f)

        self.line1 = QLineEdit(self)
        self.line1.setText('')
        self.line1.setGeometry(0, 0, 175, 50)
        self.line1.move(25, 25)

        self.line2 = QLineEdit(self)
        self.line2.setText('')
        self.line2.setGeometry(0, 0, 175, 50)
        self.line2.move(25, 200)

        self.label1 = QLabel(self)
        self.label1.setText('Первое число(целое):')
        self.label1.move(25, 0)

        self.label1 = QLabel(self)
        self.label1.setText('Второе число(целое):')
        self.label1.move(25, 175)

        self.lsds = []
        self.f = ['Сумма', 'Разность', 'Произведение', 'Частое']
        for i in range(4):
            a = QLCDNumber(self)
            self.lsds.append(a)
            a.setGeometry(0, 0, 125, 30)
            a.move(350, 25 + 75 * i)

            a = QLabel(self)
            a.setText(self.f[i])
            a.move(250, 25 + 75 * i)
Ejemplo n.º 21
0
    def initUI(self):
        self.resize(600, 500)
        self.setWindowTitle('filter_sample')
        # 画像を読み込んで、arrayにセット
        self.array = np.array(
            Image.open("sample.jpg").convert("RGBA"), np.float32)
        #print(self.array.dtype)
        # 画像を読み込んで、ラベルに貼り付け
        pixmap = QPixmap("sample.jpg")
        self.lbl = QLabel(self)
        self.lbl.setPixmap(pixmap)
        # フィルタ適用用のボタンを作って、関数にリンク
        btn1 = QPushButton("Nega", self)
        btn1.move(400, 50)
        btn1.clicked.connect(self.button_clicked1)
        btn2 = QPushButton("Brightness", self)
        btn2.move(400, 100)
        btn2.clicked.connect(self.button_clicked2)
        btn3 = QPushButton("Median", self)
        btn3.move(400, 150)
        btn3.clicked.connect(self.button_clicked3)
        btn4 = QPushButton("FFT", self)
        btn4.move(400, 170)
        btn4.clicked.connect(self.button_clicked4)

        # 数字のウィジェットを作成
        lcd = QLCDNumber(self)
        lcd.resize(150, 100)
        lcd.move(400, 200)
        # スライダーウィジェット作成
        self.sld = QSlider(Qt.Horizontal, self)
        self.sld.resize(150, 30)
        self.sld.move(400, 300)

        # スライダーを変更すると、数字も切り替わる
        self.sld.valueChanged.connect(lcd.display)
        self.sld.sliderReleased.connect(self.release_mouse)
Ejemplo n.º 22
0
    def initUI(self):

        self.statusBar()

        btn1 = QPushButton('кнопка1', self)
        btn1.clicked.connect(self.buttonClicked)
        btn1.move(50, 10)

        btn2 = QPushButton('кнопка2', self)
        btn2.clicked.connect(self.showDialog1)
        btn2.move(200, 10)

        btn3 = QPushButton('кннопка3', self)
        btn3.clicked.connect(self.showDialog)
        btn3.move(350, 10)

        lbl1 = QLabel('label1', self)
        lbl1.move(50, 50)
        self.le = QLineEdit(self)
        self.le.move(100, 50)

        lcd = QLCDNumber(self)
        lcd.move(50, 100)
        sld = QSlider(Qt.Horizontal, self)
        sld.move(50, 150)

        cb = QCheckBox('Сменить статус', self)
        cb.move(50, 200)
        cb.toggle()
        cb.stateChanged.connect(self.check)

        sld.valueChanged.connect(lcd.display)

        self.setGeometry(0, 0, 500, 300)
        self.setWindowTitle('test7')
        self.setWindowIcon(QIcon('bit.png'))
        self.show()
Ejemplo n.º 23
0
class Temperature_Page(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        self.NowTemperature = QLCDNumber(self)
        self.WantTemperature = QLCDNumber(self)
        self.SettingDial = QDial(self)
        self.lbNow = QLabel("현재 온도", self)
        self.lbWant = QLabel("희망 온도", self)
        self.NowFont = self.lbNow.font()
        self.NowFont.setPointSize(40)
        self.NowFont.setBold(True)

        self.lbNow.resize(300, 50)
        self.lbNow.move(50, 50)
        self.lbNow.setAlignment(Qt.AlignCenter)
        self.lbNow.setFont(self.NowFont)

        self.lbWant.resize(300, 50)
        self.lbWant.move(400, 50)
        self.lbWant.setAlignment(Qt.AlignCenter)
        self.lbWant.setFont(self.NowFont)

        self.NowTemperature.resize(300, 100)
        self.NowTemperature.move(50, 130)

        self.WantTemperature.resize(300, 100)
        self.WantTemperature.move(400, 130)

        self.SettingDial.resize(190, 190)
        self.SettingDial.setRange(-20, 20)
        self.SettingDial.setNotchesVisible(True)
        self.SettingDial.move(460, 250)
        self.NowTemperature.display(sensorValue)

        self.SettingDial.valueChanged.connect(self.WantTemperature.display)
Ejemplo n.º 24
0
class Game(QMainWindow):
    def __init__(self):
        super().__init__()
        self.resize(400, 430)
        self.setWindowTitle('Tetris')
        self.scores = 0
        self.tetBoard = Board(self)
        self.lcd = QLCDNumber(self)
        self.tetBoard.resize(200, 415)
        self.layout = QHBoxLayout()
        self.layout.addWidget(self.tetBoard)
        self.layout.addWidget(self.lcd)
        self.lcd.move(250, 150)
        self.setLayout(self.layout)
        self.statusbar = self.statusBar()
        self.tetBoard.msg2statusbar[str].connect(self.statusbar.showMessage)
        self.tetBoard.closeMsg.connect(self.close)
        self.tetBoard.scoresMsg.connect(self.increase)
        self.tetBoard.start()
        self.show()

    def increase(self, score):
        self.scores += score
        self.lcd.display(self.scores)
Ejemplo n.º 25
0
class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(450, 150, 450, 150)
        self.setWindowTitle('Миникалькулятор')
        self.btn = QPushButton('->', self)
        self.label1 = QLineEdit(self)
        self.label2 = QLineEdit(self)
        self.labe1 = QLabel(self)
        self.labe2 = QLabel(self)
        self.labe3 = QLabel(self)
        self.labe4 = QLabel(self)
        self.q1 = QLCDNumber(self)
        self.q2 = QLCDNumber(self)
        self.q3 = QLCDNumber(self)
        self.q4 = QLCDNumber(self)
        self.label1.move(5, 25)
        self.label2.move(5, 65)
        self.btn.resize(20, 20)
        self.btn.move(150, 55)
        self.labe1.setText("Сумма")
        self.labe2.setText("Разность")
        self.labe3.setText("Произведение")
        self.labe4.setText("Частность")
        self.labe1.move(175, 5)
        self.labe2.move(175, 35)
        self.labe3.move(175, 65)
        self.labe4.move(175, 95)
        self.q1.move(270, 5)
        self.q2.move(270, 35)
        self.q3.move(270, 65)
        self.q4.move(270, 95)
        self.btn.clicked.connect(self.nn)

    def nn(self):
        e = int(self.label1.text())
        w = int(self.label2.text())
        self.q1.display(e + w)
        self.q2.display(e - w)
        self.q3.display(e * w)
        if w != 0: self.q4.display(e / w)
Ejemplo n.º 26
0
class MyWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.resize(1300, 700)
        self.setFixedSize(self.size())
        self.setWindowTitle('PyChord')
        self.add_combo_boxes()
        self.add_buttons()
        self.sl = QSlider(Qt.Horizontal, self)
        self.volume = QLCDNumber(self)
        self.add_slider()

        self.actual_key = None
        self.actual_meter = 4
        self.actual_instrument = instrument.Piano()
        self.melody_stream = stream.Stream()
        self.harmonized_melody_stream = stream.Stream()
        self.reset_stream(self.melody_stream)
        self.reset_stream(self.harmonized_melody_stream)
        mixer.init(44100, -16, 2, 1024)

        self.tmpStream = stream.Stream()
        self.tmpStream.insert(instrument.Piano())
        self.lpc = lily.translate.LilypondConverter()
        self.lpc.context = lily.lilyObjects.LyMusicList()
        self.keyboard = Keyboard(self)
        self.melody = Melody(self, self.actual_key)

    def change_volume(self, vl):
        mixer.music.set_volume(vl / 100.0)
        self.volume.display(vl)

    def add_buttons(self):
        play_button = QPushButton('Play', self)
        play_button.move(1100, 300)
        play_button.clicked.connect(self.play_notes)

        reset_button = QPushButton('Reset', self)
        reset_button.move(1100, 350)
        reset_button.clicked.connect(self.reset)

        notes_button = QPushButton('Show Notes', self)
        notes_button.clicked.connect(self.show_notes)
        notes_button.move(1100, 400)

        save_button = QPushButton('Save', self)
        save_button.clicked.connect(self.save)
        save_button.move(1100, 450)

    def add_combo_boxes(self):
        key_info = QLabel('Choose a key:', self)
        key_info.move(600, 50)
        key_choice = QComboBox(self)
        key_choice.move(600, 100)
        key_choice.addItems(['None', 'C', 'D', 'E', 'F', 'G', 'A', 'B'])
        key_choice.currentIndexChanged.connect(self.change_key)

        meter_info = QLabel('Choose a meter:', self)
        meter_info.move(400, 50)
        meter_choice = QComboBox(self)
        meter_choice.move(400, 100)
        meter_choice.addItems(['4/4', '3/4', '2/4'])
        meter_choice.currentIndexChanged.connect(self.change_meter)

        instrument_choice = QComboBox(self)
        instrument_choice.move(1100, 250)
        instrument_choice.addItems(
            ['Piano(default)', 'Guitar', 'Violin', 'Flute', 'Mandolin'])
        instrument_choice.currentIndexChanged.connect(self.change_instrument)

    def add_slider(self):
        self.sl.setMinimum(0)
        self.sl.setMaximum(100)
        self.sl.setValue(80)
        self.sl.setTickInterval(1)
        self.sl.move(1100, 220)
        self.sl.valueChanged.connect(
            lambda: self.change_volume(self.sl.value()))

        self.volume.move(1100, 180)
        self.volume.display(80)

    def play_notes(self):
        try:
            if not self.melody.is_well_rhythmic:
                confirm = QMessageBox()
                confirm.setWindowTitle('Error')
                confirm.setText('The rhythm is not correct.')
                confirm.setIcon(QMessageBox.Information)
                confirm.exec()
            else:
                if self.actual_key is not None:
                    self.melody.harmonize()
                    mixer.music.load(
                        self.harmonized_melody_stream.write('midi'))
                    mixer.music.play()
                else:
                    mixer.music.load(self.melody_stream.write('midi'))
                    mixer.music.play()
        except exceptions21.StreamException:
            pass

    def show_notes(self):
        if not self.melody.is_well_rhythmic:
            confirm = QMessageBox()
            confirm.setWindowTitle('Error')
            confirm.setText('The rhythm is not correct.')
            confirm.setIcon(QMessageBox.Information)
            confirm.exec()
        else:
            self.lpc.context.contents = []
            self.lpc.appendObjectsToContextFromStream(self.melody_stream)

            with open('notes.ly', 'w+') as f:
                f.write('\\version "2.20.0"\n')
                if self.actual_key is None:
                    f.write("{\n")
                    f.write('\\key c \\major \n')
                    f.write(str(self.lpc.context))
                    f.write("}\n")
                else:
                    f.write('{<<\n')
                    f.write('\\chords {')
                    for i in self.melody.list_of_chords:
                        f.write(i.lower() + " ")
                    f.write('}\n')
                    f.write('{\\key ' + self.actual_key.tonic.name.lower() +
                            ' \\' + self.actual_key.mode)
                    f.write('\n')
                    f.write(str(self.lpc.context))
                    f.write('}>>}\n')

            if platform.system() == 'Linux':
                process = subprocess.Popen(['lilypond notes.ly'], shell=True)
                process.wait(100)

                subprocess.Popen(['chmod 755 notes.pdf'], shell=True)
                subprocess.Popen(['xdg-open notes.pdf'], shell=True)

            elif platform.system() == 'Windows':
                process = subprocess.Popen(['powershell', 'lilypond notes.ly'])
                process.wait(100)

                subprocess.Popen(['powershell', '.\\notes.pdf'])

    def save(self):
        if not self.melody.is_well_rhythmic:
            confirm = QMessageBox()
            confirm.setWindowTitle('Error')
            confirm.setText('The rhythm is not correct.')
            confirm.setIcon(QMessageBox.Information)
            confirm.exec()
        else:
            if not os.path.exists('music'):
                os.makedirs('music')
            today = date.today()
            flag = True
            count = 1
            path = ''

            while flag is True:
                path = os.path.join('music',
                                    '{}.{}.mid'.format(str(count), str(today)))
                flag = os.path.isfile(path)
                count += 1

            self.harmonized_melody_stream.write('midi', fp=path)
            confirm = QMessageBox()
            confirm.setWindowTitle('Confirmation')
            confirm.setText('File saved')
            confirm.setIcon(QMessageBox.Information)
            confirm.exec()

    def add_note(self, my_note):
        self.melody.rhythmic_values_sum = sum(
            self.melody.note_buttons[i].rhythmic_value
            for i in range(len(self.melody.note_buttons)))
        if self.melody.rhythmic_values_sum < self.melody.max_notes:
            self.melody_stream.insert(self.melody.rhythmic_values_sum + 2,
                                      note.Note(my_note.nameWithOctave))
            for i in range(8):
                if mixer.Channel(i).get_busy():
                    pass
                else:
                    if platform.system() == 'Linux':
                        mixer.Channel(i).play(
                            mixer.Sound('notes/{}.wav'.format(my_note)))
                    elif platform.system() == 'Windows':
                        mixer.Channel(i).play(
                            mixer.Sound('notes\\{}.wav'.format(my_note)))
                    break
            self.melody.add_note_to_melody(my_note)
            self.melody.show_melody()

    def reset_stream(self, stream_to_reset):
        stream_to_reset.clear()
        stream_to_reset.insert(0, self.actual_instrument)
        stream_to_reset.insert(
            1, meter.TimeSignature('{}/4'.format(self.actual_meter)))

    def change_instrument(self, choice):
        instruments = [
            instrument.Piano(),
            instrument.AcousticGuitar(),
            instrument.Violin(),
            instrument.Flute(),
            instrument.Mandolin()
        ]
        self.actual_instrument = instruments[choice]
        self.melody_stream[0] = self.actual_instrument

    def reset(self):
        for button in self.melody.note_buttons:
            button.hide()
        self.melody.note_buttons.clear()
        self.melody.notes_counter = 0
        self.melody.rhythmic_values_sum = 0
        self.reset_stream(self.melody_stream)
        self.reset_stream(self.harmonized_melody_stream)

    def change_key(self, choice):
        self.reset()
        self.keyboard.reset()
        if choice == 0:
            self.actual_key = None
        else:
            keys = ['None', 'C', 'D', 'E', 'F', 'G', 'A', 'B']
            self.actual_key = key.Key(keys[choice])
            self.keyboard.on_key_change(self.actual_key)

        self.melody.actual_key = self.actual_key

    def change_meter(self, choice):
        self.reset()
        meters = [4, 3, 2]
        self.actual_meter = meters[choice]
        self.melody.on_meter_change(self.actual_meter)
        self.update(0, 0, 1000, 1000)

    def paintEvent(self, e):
        lines = QPainter(self)
        lines.setPen(QPen(QColor(240, 240, 240), 10, Qt.SolidLine))
        for i in range(17):
            lines.drawLine(250 + i * 45, 290, 250 + i * 45, 350)

        lines.setPen(QPen(Qt.black, 10, Qt.SolidLine))
        for i in range(5):
            lines.drawLine(250 + i * self.actual_meter * 45, 290,
                           250 + i * self.actual_meter * 45, 350)
        lines.end()
Ejemplo n.º 27
0
class Trigan_Result_Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        global COUNT_TRUES_EQUATIONS, begin
        global COUNT_TRIES_EQUATIONS

        self.f_r = open("info", mode='r')
        self.frm = QFrame(self)
        self.frm.setStyleSheet("QWidget { background-color: %s }" %
                               self.f_r.read(7))
        self.frm.setGeometry(0, 0, 2000, 1000)

        self.setGeometry(500, 300, 400, 200)
        self.setWindowTitle('Результаты работы')

        self.lcdNumber = QLCDNumber(self)
        self.lcdNumber.setGeometry(QtCore.QRect(0, 0, 80, 35))
        self.lcdNumber.move(300, 10)
        self.lcdNumber.setNumDigits(5)
        self.str1 = "{:0>2d}:{:0>2d}".format(begin // 60, begin % 60)
        self.lcdNumber.display(self.str1)

        self.result_label = QLabel(self)
        self.result_label.setText(
            f"Ваш результат: {COUNT_TRUES_EQUATIONS} из {COUNT_TRIES_EQUATIONS}"
        )
        self.result_label.setFont(
            QtGui.QFont("Currently only TrueType fonts", 14))
        self.result_label.resize(300, 50)
        self.result_label.move(70, 70)
        self.f_r.seek(14)
        self.result_label.setStyleSheet("QLabel {color: %s;}" %
                                        self.f_r.read(7))
        COUNT_TRIES_EQUATIONS = 0
        COUNT_TRUES_EQUATIONS = 0

        begin = 0

        self.back_btn = QPushButton('← Меню', self)
        self.back_btn.resize(90, 30)
        self.back_btn.move(10, 160)
        self.f_r.seek(7)
        self.back_btn.setStyleSheet(
            "QPushButton { background-color: %s; border: %s; color: %s}" %
            (self.f_r.read(7), None, self.f_r.read(7)))

        self.qu_btn = QPushButton('↺ Заново', self)
        self.qu_btn.resize(90, 30)
        self.qu_btn.move(110, 160)
        self.f_r.seek(7)
        self.qu_btn.setStyleSheet(
            "QPushButton { background-color: %s; border: %s; color: %s}" %
            (self.f_r.read(7), None, self.f_r.read(7)))
        self.f_r.close()

        self.back_btn.clicked.connect(self.back)
        self.qu_btn.clicked.connect(self.ques)

    def back(self):
        self.back_form = MainMenu()
        self.back_form.show()
        self.close()

    def ques(self):
        self.ques_form = Trigan_Window()
        self.ques_form.show()
        self.close()
Ejemplo n.º 28
0
class Trigan_Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        global TIMER, COUNT_ARRAY
        global TIME_COUNT, array

        TIMER = 1

        self.f_r = open("info", mode='r')
        self.frm = QFrame(self)
        self.frm.setStyleSheet("QWidget { background-color: %s }" %
                               self.f_r.read(7))
        self.frm.setGeometry(0, 0, 2000, 1000)

        self.setGeometry(400, 200, 500, 450)
        self.setWindowTitle('Формулы приведения')

        con = sqlite3.connect("name_users.db")
        cur = con.cursor()

        self.answer_name_label = QLabel(self)
        self.answer_name_label.setText("Введите ваш ответ: ")
        self.answer_name_label.resize(250, 50)
        self.answer_name_label.move(0, 380)
        self.f_r.seek(14)
        self.answer_name_label.setStyleSheet("QLabel {color: %s;}" %
                                             self.f_r.read(7))

        self.rec_btn = QPushButton('Следующий', self)
        self.rec_btn.resize(480, 170)
        self.rec_btn.move(10, 200)
        self.f_r.seek(7)
        self.rec_btn.setStyleSheet(
            "QPushButton { background-color: %s; border: %s; color: %s}" %
            (self.f_r.read(7), None, self.f_r.read(7)))
        self.f_r.close()

        font = QtGui.QFont()
        font.setPointSize(17)
        self.rec_btn.setFont(font)

        self.rec_btn.clicked.connect(self.recursion)

        result = cur.execute("""SELECT * FROM Trigonometry
                                                            WHERE Way like '%'"""
                             )
        if COUNT_ARRAY == 0:
            array = list(result)
            random.shuffle(array)

        self.true_answers = []
        self.player_answers = []

        self.way = array[COUNT_ARRAY]
        self.true_answers.append(self.way[1])

        self.pixmap = QPixmap(self.way[0])
        self.image = QLabel(self)
        self.image.move(85, 10)
        self.image.resize(330, 160)
        self.image.setPixmap(self.pixmap)

        self.answer_input = QLineEdit(self)
        self.answer_input.resize(150, 30)
        self.answer_input.move(160, 390)

        self.player_answers.append(self.answer_input.text())

        self.lcdNumber = QLCDNumber(self)
        self.lcdNumber.setGeometry(QtCore.QRect(0, 0, 80, 35))
        self.lcdNumber.move(400, 390)
        self.lcdNumber.setNumDigits(5)
        self.str1 = "{:0>2d}:{:0>2d}".format(begin // 60, begin % 60)
        self.lcdNumber.display(self.str1)

        self.timer = QTimer(self)
        self.timer.timeout.connect(self.showTime)
        self.timer.start(1000)

        con.commit()
        con.close()

    def recursion(self):
        global COUNT_TRIES_EQUATIONS, begin
        global COUNT_TRUES_EQUATIONS, COUNT_ARRAY

        self.timer.stop()

        if str(self.answer_input.text()) == str(self.true_answers[-1]):
            COUNT_TRUES_EQUATIONS += 1

        COUNT_TRIES_EQUATIONS += 1
        COUNT_ARRAY += 1

        if COUNT_TRIES_EQUATIONS < 32:
            self.rec_form = Trigan_Window()
            self.rec_form.show()
            self.close()
        else:
            COUNT_ARRAY = 0
            self.res_form = Trigan_Result_Window()
            self.res_form.show()
            self.close()

    def showTime(self):
        global begin
        begin = begin + 1
        self.str1 = "{:0>2d}:{:0>2d}:{:0>2d}".format(begin // 3600,
                                                     (begin % 3600) // 60,
                                                     begin % 60)
        self.lcdNumber.display(self.str1)
Ejemplo n.º 29
0
class The_Main_Window(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(550, 150, 650, 350)
        self.setWindowTitle("World of Words")
        self.setStyleSheet(
            "background-color: #EEE8AA; color: #191970; font-family: Times;")

        self.table = QLCDNumber(self)
        self.table.setStyleSheet(
            'QLCDNumber {background-color: #FFB6C1; color: #191970;}')
        self.table.display('')
        self.table.move(10, 20)
        self.table.resize(380, 50)

        # Когда пользователь будет нажимать на эту кнопку, будет происходить транслитерация
        self.the_main_btn = QPushButton("Нажмите, когда введёте слово", self)
        self.the_main_btn.setStyleSheet(
            'QPushButton {background-color: #8FBC8F; color: #191970;}')
        self.the_main_btn.resize(self.the_main_btn.sizeHint())
        self.the_main_btn.move(10, 120)
        self.the_main_btn.clicked.connect(self.coding)

        self.label = QLabel(self)
        self.label.setText("Здесь отобразится готовый текст")
        self.label.setStyleSheet(
            'QLabel {background-color: #FFB6C1; color: #191970;}')
        self.label.move(20, 30)
        font = QFont('CyrillicOld', 10)
        self.label.setFont(font)

        self.word_label = QLabel(self)
        self.word_label.setText("Введите слово: ")
        self.word_label.move(10, 90)

        self.word_input = QLineEdit(self)
        self.word_input.move(100, 90)
        self.word_input.resize(290, 20)

        self.table2 = QLabel(self)
        self.table2.move(20, 200)
        self.table2.resize(480, 20)

        self.table3 = QLabel(self)
        self.table3.move(20, 230)
        self.table3.resize(480, 20)

        self.table4 = QLabel(self)
        self.table4.move(20, 260)
        self.table4.resize(480, 20)

        self.table5 = QLabel(self)
        self.table5.move(20, 290)
        self.table5.resize(480, 20)

        self.ad_area = QLabel(self)
        self.ad_area.setText(
            "Здесь Вы можете увидеть некоторую информацию о слове:")
        self.ad_area.move(10, 180)
        font = QFont('CyrillicOld', 9)
        self.ad_area.setFont(font)

        self.btn_for_info = QPushButton(
            "Нажмите, чтобы увидеть данные об этом слове", self)
        self.btn_for_info.setStyleSheet(
            'QPushButton {background-color: #8FBC8F; color: #191970;}')
        self.btn_for_info.resize(self.btn_for_info.sizeHint())
        self.btn_for_info.move(10, 150)
        self.btn_for_info.clicked.connect(self.give_info)

        self.pixmap = QPixmap()
        self.image = QLabel(self)
        self.image.move(405, 17)
        self.image.resize(230, 200)
        self.image.setPixmap(self.pixmap)

    def coding(self):
        self.d = {
            'А': 'A',
            'Б': 'B',
            'В': 'V',
            'Г': 'G',
            'Д': 'D',
            'Е': 'E',
            'Ё': 'E',
            'Ж': 'Zh',
            'З': 'Z',
            'И': 'I',
            'Й': 'I',
            'К': 'K',
            'Л': 'L',
            'М': 'M',
            'Н': 'N',
            'О': 'O',
            'П': 'P',
            'Р': 'R',
            'С': 'S',
            'Т': 'T',
            'У': 'U',
            'Ф': 'F',
            'Х': 'Kh',
            'Ц': 'Tc',
            'Ч': 'Ch',
            'Ш': 'Sh',
            'Щ': 'Shch',
            'Ы': 'Y',
            'Э': 'E',
            'Ю': 'Iu',
            'Я': 'Ia',
            'а': 'a',
            'б': 'b',
            'в': 'v',
            'г': 'g',
            'д': 'd',
            'е': 'e',
            'ё': 'e',
            'ж': 'zh',
            'з': 'z',
            'и': 'i',
            'й': 'i',
            'к': 'k',
            'л': 'l',
            'м': 'm',
            'н': 'n',
            'о': 'o',
            'п': 'p',
            'р': 'r',
            'с': 's',
            'т': 't',
            'у': 'u',
            'ф': 'f',
            'х': 'kh',
            'ц': 'tc',
            'ч': 'ch',
            'ш': 'sh',
            'щ': 'shch',
            'ы': 'y',
            'э': 'e',
            'ю': 'iu',
            'я': 'ia'
        }

        origin = self.word_input.text().lower()
        if not all(symbol in 'йцукенгшщзхъфывапролджэячсмитьбюё'
                   or symbol in '1234567890-_=+*&^%$#@!~№;,<.>":?\/ |'
                   for symbol in origin):
            self.label.setText('Ой!!!')
            self.translit = origin
        else:
            answ = self.word_input.text()
            ans = ''
            for i in answ:
                if i in self.d:
                    ans += self.d[i]
                elif i != 'ь' and i != 'Ь' and i != 'ъ' and i != 'Ъ':
                    ans += i
            self.label.setText("{}".format(ans))
            self.translit = ans

    def give_info(self):
        # В этом методе мы будем сравнивать оригинал и транлитерацию по некоторым параметрам
        word_in_translit = self.translit.lower()
        word_in_Russian = self.word_input.text().lower()

        # Если пользователь ввел неподходящее слово или фразу, то мы не транслитерируем и уведомляем его об этом (было в т.ч. до этого)
        if word_in_translit == word_in_Russian:
            self.table2.setText("Ой, что-то пошло не так, поробуйте снова...")
            self.table3.setText("Возможно, Вы не поменяли раскладку...")
        else:
            self.table2.setText("Оригинал: {};  транслитерация: {}".format(
                word_in_Russian, word_in_translit))
            self.table3.setText(
                "Количество символов в оригинале: {};  в транслитерации: {}".
                format(len(word_in_Russian), len(word_in_translit)))

        # Списки букв, гласных и согласных в русском и английском алфавитах
        letters_engl = [chr(i) for i in range(ord('a'), ord('z') + 1)]
        letters_rus = [chr(i) for i in range(ord('а'), ord('я') + 1)]
        vowels_engl = ['a', 'u', 'e', 'o', 'y', 'i']
        vowels_rus = ['а', 'у', 'о', 'е', 'и', 'я', 'ю', 'ё', 'э', 'ы']
        cons_engl = list(
            filter(lambda letter: letter not in vowels_engl, letters_engl))
        cons_rus = list(
            filter(lambda letter: letter not in vowels_rus, letters_rus))

        # Защита от дурака, который ввел слово не на русском или с отличными от русских букв и приведенных ниже символов
        if not all(symbol in letters_rus
                   or symbol in '1234567890-_=+*&^%$#@!~№;,<.>":?\/ |'
                   for symbol in word_in_Russian):
            # Похоже на одно сообщение в несколько строк
            self.table4.setText("Или ввели недопустимые символы..")
            self.table5.setText("Будьте внимательней :))))")
            self.pixmap.load("картинка для ошибки.jpg")
            self.image.setPixmap(self.pixmap)

        else:
            # Она сделана под цвет фона, и её не видно
            self.pixmap.load("картинка на случай не ошибки.jpg")
            self.image.setPixmap(self.pixmap)
            # self.image.resize(1, 1)
            # Непосредственно нахождение количества тех или иных букв в словах
            # Сначала создали список со всеми нужными буквами, чтобы не потерять их
            vow_engl_in_word = list(
                filter(lambda letter: letter in vowels_engl, word_in_translit))
            num_of_vow_engl_in_word = len(vow_engl_in_word)
            vow_rus_in_word = list(
                filter(lambda letter: letter in vowels_rus, word_in_Russian))
            num_of_vow_rus_in_word = len(vow_rus_in_word)
            cons_engl_in_word = list(
                filter(lambda letter: letter in cons_engl, word_in_translit))
            num_of_cons_engl_in_word = len(cons_engl_in_word)
            cons_rus_in_word = list(
                filter(lambda letter: letter in cons_rus, word_in_Russian))
            num_of_cons_rus_in_word = len(cons_rus_in_word)

            self.table4.setText(
                "Количество гласных звуков в русской версии: {};  в транслитерированной версии: {}"
                .format(num_of_vow_rus_in_word, num_of_vow_engl_in_word))
            self.table5.setText(
                "Количество согласных звуков в русской версии: {};  в транслитерированной версии: {}"
                .format(num_of_cons_rus_in_word, num_of_cons_engl_in_word))
Ejemplo n.º 30
0
class Main(QWidget):

    started = False
    speed = 1000
    backWidth = 10
    backHeight = 20
    blockOffset = 35
    blockSize = 30

    background = None
    currentShape = None
    nextShape = None
    factory = sf.ShapeFactory()

    score = 0

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.resize(560, 700)
        self.center()
        self.setWindowTitle('Teris')

        nextLabel = QLabel('下一个方块:', self)
        nextLabel.setFont(QFont("Roman times", 16, QFont.Bold))
        nextLabel.move((self.backWidth + 3) * self.blockSize, 30)

        scoreLabel = QLabel('当前得分:', self)
        scoreLabel.setFont(QFont("Roman times", 16, QFont.Bold))
        scoreLabel.move((self.backWidth + 3) * self.blockSize, 230)

        self.scoreNumber = QLCDNumber(self)
        self.scoreNumber.move((self.backWidth + 3) * self.blockSize, 260)
        self.scoreNumber.setSegmentStyle(QLCDNumber.Flat)
        self.scoreNumber.setStyleSheet(
            "font-size: 30px; color: red; border: 1px solid black; height: 100px; width: 100px;"
        )

        self.timer = QBasicTimer()
        self.background = bg.Background(self.backWidth, self.backHeight,
                                        self.blockSize, self.blockOffset)
        self.productShape()
        self.startHandler()
        self.show()

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def paintEvent(self, event):
        qp = QPainter()
        qp.begin(self)
        self.background.draw(qp)
        self.currentShape.draw(qp)
        self.nextShape.draw(qp)
        qp.end()

    def reDraw(self):
        self.update()

    def keyPressEvent(self, event):
        key = event.key()
        if key == Qt.Key_Left:
            self.leftHandler()
        elif key == Qt.Key_Right:
            self.rightHandler()
        elif key == Qt.Key_Down:
            self.downHandler()
        elif key == Qt.Key_Up:
            self.upHandler()
        elif key == Qt.Key_P:
            self.startHandler()
        elif key == Qt.Key_Space:
            self.downoverHandler()

    def timerEvent(self, event):
        if event.timerId() == self.timer.timerId():
            self.downHandler()
        else:
            super(QWidget, self).timerEvent(event)

    def upHandler(self):
        if self.background.isRotate(self.currentShape):
            self.currentShape.changeType()
            self.reDraw()

    def leftHandler(self):
        if self.background.isLeft(self.currentShape):
            self.currentShape.changeX(-1)
            self.reDraw()

    def rightHandler(self):
        if self.background.isRight(self.currentShape):
            self.currentShape.changeX(1)
            self.reDraw()

    def downHandler(self):
        if self.background.isDown(self.currentShape):
            self.currentShape.changeY(1)
            self.reDraw()
        else:
            self.scoreShape()
            self.productShape()

    def downoverHandler(self):
        while self.background.isDown(self.currentShape):
            self.currentShape.changeY(1)
        self.scoreShape()
        self.productShape()

    # 计算得分
    def scoreShape(self):
        self.background.copyShapeDate(self.currentShape)
        self.score += self.background.scoreShape()
        self.reDraw()
        self.scoreNumber.display(self.score)
        print('score = %d' % self.score)

    def productShape(self):
        if self.nextShape:
            self.currentShape = self.factory.next(self.nextShape.color,
                                                  self.nextShape.data,
                                                  self.blockSize,
                                                  self.blockOffset)
        else:
            self.currentShape = self.factory.product(self.blockSize,
                                                     self.blockOffset)
        self.nextShape = self.factory.product(self.blockSize, 0)
        self.nextShape.offsetX = (self.backWidth + 3) * self.blockSize
        self.nextShape.offsetY = 2 * self.blockSize
        self.nextShape.border = 0x000000

    def startHandler(self):
        print('pauseHandler %s' % self.started)
        if self.started:
            self.timer.stop()
            self.started = False
        else:
            self.timer.start(self.speed, self)
            self.started = True
        self.update()
Ejemplo n.º 31
0
class TimerWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        # Инициализируем плеер и плейлист, на котором поставим цикличное воспроизведение
        self.playlist = QMediaPlaylist(self)
        self.playlist.setPlaybackMode(QMediaPlaylist.Loop)
        self.player = QMediaPlayer()
        # Создадим пустую ссылку, чтобы программа не крашилась, если пользователь не выберет мелодию
        self.url = QUrl()
        # Подскажем для чего кнопка
        self.lbl = QLabel('Выберите мелодию для таймера:', self)
        self.lbl.move(165, 100)
        # Кнопка для выбора файла с мелодией
        self.btn_getfile = QPushButton('Выбрать файл', self)
        self.btn_getfile.move(200, 125)
        self.btn_getfile.resize(100, 50)
        self.btn_getfile.clicked.connect(self.getfile)
        # Кнопка старта таймера
        self.btn_start = QPushButton('Старт', self)
        self.btn_start.move(225, 225)
        self.btn_start.resize(50, 50)
        self.btn_start.clicked.connect(self.start_timer)
        # Кнопка остановки таймера до того, как он закончит отсчет
        self.btn_stop = QPushButton('Стоп', self)
        self.btn_stop.move(250, 225)
        self.btn_stop.resize(50, 50)
        self.btn_stop.clicked.connect(self.stop_timer)
        self.btn_stop.setVisible(False)
        # Кнопка паузы таймера
        self.btn_pause = QPushButton('Пауза', self)
        self.btn_pause.move(200, 225)
        self.btn_pause.resize(50, 50)
        self.btn_pause.clicked.connect(self.pause_timer)
        self.btn_pause.setVisible(False)
        # Кнопка для продолжения отсчета таймера
        self.btn_continue = QPushButton('Дальше', self)
        self.btn_continue.move(200, 225)
        self.btn_continue.resize(50, 50)
        self.btn_continue.clicked.connect(self.continue_timer)
        self.btn_continue.setVisible(False)
        # Кнопка для выключения таймера, когда он закончит отсчет
        self.btn_off = QPushButton('Выкл', self)
        self.btn_off.move(225, 225)
        self.btn_off.resize(50, 50)
        self.btn_off.clicked.connect(self.timer_off)
        self.btn_off.setVisible(False)
        # Спрашивваем значение таймера
        self.get_timer = QTimeEdit(self)
        self.get_timer.move(185, 175)
        self.get_timer.resize(130, 50)
        self.get_timer.setFont(QFont('Times', 15, QFont.Bold))
        self.get_timer.setDisplayFormat('HH:mm:ss')
        # Дисплей для вывода таймера
        self.dsp = QLCDNumber(self)
        self.dsp.resize(200, 50)
        self.dsp.move(150, 175)
        self.dsp.setVisible(False)
        self.dsp.setDigitCount(8)
        # Таймер
        self.nTimer = QTimer()
        self.nTimer.timeout.connect(self.timer)

    def initUI(self):
        self.setGeometry(100, 100, 500, 500)
        self.setWindowTitle('Таймер')

    def start_timer(self):
        # Добавляем мелодию в плеер
        self.content = QMediaContent(self.url)
        self.playlist.addMedia(self.content)
        self.player.setPlaylist(self.playlist)
        # Выводим начальное значение времени на дисплей
        self.dsp.display(self.get_timer.time().toString('hh:mm:ss'))
        # Переводим время в секунды
        timer = self.get_timer.time()
        timer_text = timer.toString('hh:mm:ss')
        timer_int = list(map(lambda x: int(x), timer_text.split(':')))
        self.timer_in_sec = timer_int[0]*3600 + timer_int[1]*60 + timer_int[2]
        # Проверяем не установили ли нулевое значение
        if self.timer_in_sec == 0:
            self.timer_timeout()
        else:
            # Запускаем таймер
            self.nTimer.start(1000)
            # Махинации с показом кнопок
            self.btn_start.setVisible(False)
            self.btn_pause.setVisible(True)
            self.btn_stop.setVisible(True)
            self.dsp.setVisible(True)
            self.get_timer.setVisible(False)
            self.lbl.setVisible(False)
            self.btn_getfile.setVisible(False)

    def timer(self):
        # Функция обновления таймера и дисплея со временем
        # Делаем обратный отсчет, отнимая каждую секунду единицу из начального значения
        self.timer_in_sec -= 1
        # Переводим целочисленные значения в строку
        timer_text = list(map(lambda x: str(x), [self.timer_in_sec // 3600,
                                                 (self.timer_in_sec % 3600) // 60,
                                                 (self.timer_in_sec % 3600) % 60]))
        # Если один символ, то к нему добавляется ноль
        if len(timer_text[0]) == 1:
            timer_text[0] = '0' + timer_text[0]
        if len(timer_text[1]) == 1:
            timer_text[1] = '0' + timer_text[1]
        if len(timer_text[2]) == 1:
            timer_text[2] = '0' + timer_text[2]
        # Объединяем список в формат hh:mm:ss
        timer_text = ':'.join(timer_text)
        # Выводим текст со временем на дисплей
        self.dsp.display(timer_text)
        # Если таймер дошел до нуля:
        if self.timer_in_sec == 0:
            self.timer_timeout()
        else:
            # Обновляем таймер
            self.nTimer.start(1000)

    def stop_timer(self):
        # Останавливаем таймер
        self.nTimer.stop()
        # Махинации с кнопками
        self.btn_start.setVisible(True)
        self.btn_stop.setVisible(False)
        self.btn_pause.setVisible(False)
        self.dsp.setVisible(False)
        self.btn_continue.setVisible(False)
        self.get_timer.setVisible(True)
        self.btn_getfile.setVisible(True)
        self.lbl.setVisible(True)

    def continue_timer(self):
        # Продолжаем таймер с того места, где остановились
        self.nTimer.start(self.inter)
        # Махинации с показом кнопок
        self.btn_continue.setVisible(False)
        self.btn_pause.setVisible(True)

    def pause_timer(self):
        # Ловим оставшееся время таймера
        self.inter = self.nTimer.remainingTime()
        # Останавливаем таймер и делаем махинации с показом кнопок
        self.nTimer.stop()
        self.btn_pause.setVisible(False)
        self.btn_continue.setVisible(True)

    def timer_off(self):
        # Махинации с кнопками
        self.btn_start.setVisible(True)
        self.dsp.setVisible(False)
        self.get_timer.setVisible(True)
        self.btn_off.setVisible(False)
        self.btn_getfile.setVisible(True)
        self.lbl.setVisible(True)
        # Останавливаем мелодию
        self.player.stop()

    def timer_timeout(self):
        # Останавливаем таймер
        self.nTimer.stop()
        # Махинации с кнопками
        self.get_timer.setVisible(False)
        self.btn_stop.setVisible(False)
        self.btn_pause.setVisible(False)
        self.btn_continue.setVisible(False)
        self.btn_off.setVisible(True)
        self.dsp.setVisible(True)
        self.lbl.setVisible(False)
        self.btn_getfile.setVisible(False)
        # Запускаем функцию воспроизведения мелодии
        self.playmus()

    def playmus(self):
        # Воспроизводим мелодию
        self.player.play()

    def getfile(self):
        # Достаем файл с мелодией и сохраняем её путь
        fname = QFileDialog.getOpenFileName(self, 'Open File', '/home', 'Audio Files (*mp3 *wav)')
        self.url = QUrl.fromLocalFile(fname[0])
Ejemplo n.º 32
0
class Example(QWidget):
    def paintEvent(self, e):
        self.qp.begin(self)
        self.draw()
        self.qp.end()

    def __init__(self):
        super().__init__()

        self.elements = []
        """
        self.elements: QGraphicsObject[]
        """

        self.scene = QGraphicsScene()
        self.graphicsView = QGraphicsView(self.scene)

        hbox = QHBoxLayout()
        hbox.addWidget(self.graphicsView)
        # hbox.addWidget(self.wid)
        vbox = QVBoxLayout()
        vbox.addStretch(1)
        vbox.addLayout(hbox)
        self.setLayout(vbox)

        self.setGeometry(300, 300, 500, 500)
        self.setWindowTitle('My first app')

        font = QFont('Ubuntu', 20, QFont.Normal)
        self.scene.setFont(font)

        self.qp = QPainter(self.graphicsView)

        self.lcd = QLCDNumber(self.graphicsView)

        self.slider = QSlider(self.graphicsView)
        self.slider.setOrientation(Qt.Horizontal)
        self.slider.setGeometry(0,
                                self.graphicsView.height() - 30,
                                self.graphicsView.width(), 30)
        self.slider.valueChanged.connect(self.changer)

        self.elements.append(self.scene.addText('@!#'))

        self.show()

    def changer(self, e: int):
        self.lcd.display(e)
        # self.wid.testDraw(e)
        # self.graphicsView.
        font = QFont('Ubuntu', e * 2 + 16, QFont.Bold)
        self.elements[0].setFont(font)  # dynamic change

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Q:
            exit(0)
            # print(event.key())

    def draw(self):

        self.graphicsView.setGeometry(0, 0, self.width(), self.height())

        self.lcd.move(self.graphicsView.width() - self.lcd.width() - 4, 3)

        # self.qp.qp.drawLine(0, 0, 100, 200)
        # self.qp.drawText(80, 80, "@!#")
        # self.qp.qp.drawArc(50, 50, 20, 20, 100, 4000)
        # self.qp.qp.drawPie(50, 50, 20, 20, 100, 4000)
        # self.qp.qp.drawRect(1,2, self.graphicsView.width() - 4, self.graphicsView.height() - 3)
        self.slider.setGeometry(0,
                                self.graphicsView.height() - 30,
                                self.graphicsView.width(), 30)
Ejemplo n.º 33
0
class Window1(QWidget):
    def __init__(self):
        super(Window1, self).__init__()
        self.setWindowTitle('Вычисление площади')
        self.initUI()

    def initUI(self):
        self.setGeometry(200, 200, 600, 500)

        self.btnhsquare = QPushButton('Высота и сторона', self)
        self.btnhsquare.resize(200, 50)
        self.btnhsquare.move(50, 100)
        self.btnhsquare.clicked.connect(self.hsquare)

        self.btnssquare = QPushButton('По трём сторонам', self)
        self.btnssquare.resize(200, 50)
        self.btnssquare.move(50, 150)
        self.btnssquare.clicked.connect(self.ssquare)

        self.btnasquare = QPushButton('Угол и прилежащие стороны', self)
        self.btnasquare.resize(200, 50)
        self.btnasquare.move(50, 200)
        self.btnasquare.clicked.connect(self.asquare)

        self.btnisquare = QPushButton('Радиус вписанной окружности', self)
        self.btnisquare.resize(200, 50)
        self.btnisquare.move(50, 250)
        self.btnisquare.clicked.connect(self.isquare)

        self.btncsquare = QPushButton('Радиус описанной окружности', self)
        self.btncsquare.resize(200, 50)
        self.btncsquare.move(50, 300)
        self.btncsquare.clicked.connect(self.csquare)

        self.title = QLabel(self)
        self.title.setText('Выберите вариант вычисления площади:')
        self.title.move(50, 50)
        self.title.setFont(QFont('TimesNewRoman', 15))

        self.h = QLabel(self)
        self.h.setFont(QFont('TimesNewRoman', 12))
        self.h.setText('Высотак стороне а:')
        self.h.move(300, 100)

        self.inputh = QLineEdit(self)
        self.inputh.move(450, 100)

        self.a = QLabel(self)
        self.a.setFont(QFont('TimesNewRoman', 12))
        self.a.setText('Сторона а:')
        self.a.move(300, 120)

        self.inputa = QLineEdit(self)
        self.inputa.move(450, 120)

        self.b = QLabel(self)
        self.b.setFont(QFont('TimesNewRoman', 12))
        self.b.setText('Сторона b:')
        self.b.move(300, 140)

        self.inputb = QLineEdit(self)
        self.inputb.move(450, 140)

        self.c = QLabel(self)
        self.c.setFont(QFont('TimesNewRoman', 12))
        self.c.setText('Сторона c:')
        self.c.move(300, 160)

        self.inputc = QLineEdit(self)
        self.inputc.move(450, 160)

        self.A = QLabel(self)
        self.A.setFont(QFont('TimesNewRoman', 12))
        self.A.setText('Угол А:')
        self.A.move(300, 180)

        self.inputA = QLineEdit(self)
        self.inputA.move(450, 180)

        self.B = QLabel(self)
        self.B.setFont(QFont('TimesNewRoman', 12))
        self.B.setText('Угол В:')
        self.B.move(300, 200)

        self.inputB = QLineEdit(self)
        self.inputB.move(450, 200)

        self.C = QLabel(self)
        self.C.setFont(QFont('TimesNewRoman', 12))
        self.C.setText('Угол С:')
        self.C.move(300, 220)

        self.inputC = QLineEdit(self)
        self.inputC.move(450, 220)

        self.r = QLabel(self)
        self.r.setFont(QFont('TimesNewRoman', 12))
        self.r.setText('Радиус вписанной окружности:')
        self.r.move(300, 240)

        self.inputr = QLineEdit(self)
        self.inputr.move(450, 265)

        self.R = QLabel(self)
        self.R.setFont(QFont('TimesNewRoman', 12))
        self.R.setText('Радиус описанной окружности:')
        self.R.move(300, 285)

        self.inputR = QLineEdit(self)
        self.inputR.move(450, 310)

        self.S = QLabel(self)
        self.S.setText('Площадь:')
        self.S.setFont(QFont('TimesNewRoman', 20))
        self.S.move(100, 425)

        self.error = QLabel(self)
        self.error.setFont(QFont('TimesNewRoman', 20))
        self.error.setText('Введены неверные данные')
        self.error.move(3000, 1000)

        self.LCD_count = QLCDNumber(self)
        self.LCD_count.move(300, 435)

    def hsquare(self):
        self.error.move(3000, 1000)
        try:
            h = float(self.inputh.text())
            a = float(self.inputa.text())
            self.LCD_count.display(0.5 * h * a)
        except Exception:
            self.error.move(150, 375)

    def ssquare(self):
        self.error.move(3000, 1000)
        try:
            a = float(self.inputa.text())
            b = float(self.inputb.text())
            c = float(self.inputc.text())
            p = (a + b + c) / 2
            self.LCD_count.display((p * (p - a) * (p - b) * (p - c)) ** 0.5)
        except Exception:
            self.error.move(150, 375)

    def asquare(self):
        self.error.move(3000, 1000)
        try:
            a = float(self.inputa.text())
            b = float(self.inputb.text())
            C = float(self.inputC.text())
            self.LCD_count.display(0.5 * math.sin(math.pi * C / 180) * a * b)
        except Exception:
            self.error.move(150, 375)

    def isquare(self):
        self.error.move(3000, 1000)
        try:
            a = float(self.inputa.text())
            b = float(self.inputb.text())
            c = float(self.inputc.text())
            p = (a + b + c) / 2
            r = float(self.inputr.text())
            self.LCD_count.display(r * p)
        except Exception:
            self.error.move(150, 375)

    def csquare(self):
        self.error.move(3000, 1000)
        try:
            a = float(self.inputa.text())
            b = float(self.inputb.text())
            c = float(self.inputc.text())
            R = float(self.inputR.text())
            self.LCD_count.display(a * b * c / (4 * R))
        except Exception:
            self.error.move(150, 375)
Ejemplo n.º 34
0
class Window6(QWidget):
    def __init__(self):
        super(Window6, self).__init__()
        self.setWindowTitle('Вычисление длины биссектрисы')
        self.initUI()

    def initUI(self):
        self.setGeometry(200, 200, 600, 300)

        self.title = QLabel(self)
        self.title.setText('Выберите способ вычисления биссектрисы:')
        self.title.move(50, 50)
        self.title.setFont(QFont('TimesNewRoman', 15))

        self.a = QLabel(self)
        self.a.setFont(QFont('TimesNewRoman', 12))
        self.a.setText('Сторона а:')
        self.a.move(50, 100)

        self.inputa = QLineEdit(self)
        self.inputa.move(200, 100)

        self.b = QLabel(self)
        self.b.setFont(QFont('TimesNewRoman', 12))
        self.b.setText('Сторона b:')
        self.b.move(50, 120)

        self.inputb = QLineEdit(self)
        self.inputb.move(200, 120)

        self.c = QLabel(self)
        self.c.setFont(QFont('TimesNewRoman', 12))
        self.c.setText('Сторона c:')
        self.c.move(50, 140)

        self.inputc = QLineEdit(self)
        self.inputc.move(200, 140)

        self.C = QLabel(self)
        self.C.setFont(QFont('TimesNewRoman', 12))
        self.C.setText('Угол C:')
        self.C.move(50, 160)

        self.inputC = QLineEdit(self)
        self.inputC.move(200, 160)

        self.r = QLabel(self)
        self.r.setText('Биссекриса к стороне с:')
        self.r.setFont(QFont('TimesNewRoman', 15))
        self.r.move(100, 200)

        self.LCD_count = QLCDNumber(self)
        self.LCD_count.move(300, 235)

        self.btn1 = QPushButton('По трём сторонам', self)
        self.btn1.resize(200, 40)
        self.btn1.move(350, 100)
        self.btn1.clicked.connect(self.sides)

        self.btn1 = QPushButton('По двум сторонам и углу', self)
        self.btn1.resize(200, 40)
        self.btn1.move(350, 150)
        self.btn1.clicked.connect(self.angleside)

        self.error = QLabel(self)
        self.error.setFont(QFont('TimesNewRoman', 20))
        self.error.setText('Введены неверные данные')
        self.error.move(3000, 1000)

    def sides(self):
        self.error.move(3000, 1000)
        try:
            a = float(self.inputa.text())
            b = float(self.inputb.text())
            c = float(self.inputc.text())

            self.LCD_count.display((a * b * (a + b + c) * (a + b - c)) ** 0.5 / (a + b))
        except Exception:
            self.error.move(120, 260)

    def angleside(self):
        self.error.move(3000, 1000)
        try:
            a = float(self.inputa.text())
            b = float(self.inputb.text())
            C = float(self.inputC.text())

            self.LCD_count.display(a * b * math.cos(math.pi * (С / 2) / 180) / (a + b))
        except Exception:
            self.error.move(120, 260)
Ejemplo n.º 35
0
class Window5(QWidget):
    def __init__(self):
        super(Window5, self).__init__()
        self.setWindowTitle('Вычисление высоты треугольника')
        self.initUI()

    def initUI(self):
        self.setGeometry(200, 200, 600, 300)

        self.title = QLabel(self)
        self.title.setText('Выберите способ вычисления высоты:')
        self.title.move(50, 50)
        self.title.setFont(QFont('TimesNewRoman', 15))

        self.a = QLabel(self)
        self.a.setFont(QFont('TimesNewRoman', 12))
        self.a.setText('Сторона а:')
        self.a.move(50, 100)

        self.inputa = QLineEdit(self)
        self.inputa.move(200, 100)

        self.b = QLabel(self)
        self.b.setFont(QFont('TimesNewRoman', 12))
        self.b.setText('Сторона b:')
        self.b.move(50, 120)

        self.inputb = QLineEdit(self)
        self.inputb.move(200, 120)

        self.c = QLabel(self)
        self.c.setFont(QFont('TimesNewRoman', 12))
        self.c.setText('Сторона c:')
        self.c.move(50, 140)

        self.inputc = QLineEdit(self)
        self.inputc.move(200, 140)

        self.B = QLabel(self)
        self.B.setFont(QFont('TimesNewRoman', 12))
        self.B.setText('Угол В:')
        self.B.move(50, 160)

        self.inputB = QLineEdit(self)
        self.inputB.move(200, 160)

        self.r = QLabel(self)
        self.r.setText('Высота к стороне а:')
        self.r.setFont(QFont('TimesNewRoman', 15))
        self.r.move(100, 200)

        self.LCD_count = QLCDNumber(self)
        self.LCD_count.move(300, 235)

        self.btn1 = QPushButton('По трём сторонам', self)
        self.btn1.resize(200, 40)
        self.btn1.move(350, 100)
        self.btn1.clicked.connect(self.sides)

        self.btn1 = QPushButton('По стороне и углу', self)
        self.btn1.resize(200, 40)
        self.btn1.move(350, 150)
        self.btn1.clicked.connect(self.angleside)

        self.error = QLabel(self)
        self.error.setFont(QFont('TimesNewRoman', 20))
        self.error.setText('Введены неверные данные')
        self.error.move(3000, 1000)

    def sides(self):
        self.error.move(3000, 1000)
        try:
            a = float(self.inputa.text())
            b = float(self.inputb.text())
            c = float(self.inputc.text())
            p = (a + b + c) / 2

            self.LCD_count.display(2 * (p * (p - a) * (p - b) * (p - c)) ** 0.5 / a)
        except Exception:
            self.error.move(120, 260)

    def angleside(self):
        self.error.move(3000, 1000)
        try:
            b = float(self.inputb.text())
            B = float(self.inputB.text())

            self.LCD_count.display(b * math.sin(math.pi * B / 180))
        except Exception:
            self.error.move(120, 260)
Ejemplo n.º 36
0
class Window4(QWidget):
    def __init__(self):
        super(Window4, self).__init__()
        self.setWindowTitle('Вычисление радиуса описанной оружности')
        self.initUI()

    def initUI(self):
        self.setGeometry(200, 200, 600, 300)

        self.title = QLabel(self)
        self.title.setText('Вычислите радиус описанной окружности:')
        self.title.move(50, 50)
        self.title.setFont(QFont('TimesNewRoman', 15))

        self.a = QLabel(self)
        self.a.setFont(QFont('TimesNewRoman', 12))
        self.a.setText('Сторона а:')
        self.a.move(50, 120)

        self.inputa = QLineEdit(self)
        self.inputa.move(200, 120)

        self.b = QLabel(self)
        self.b.setFont(QFont('TimesNewRoman', 12))
        self.b.setText('Сторона b:')
        self.b.move(50, 140)

        self.inputb = QLineEdit(self)
        self.inputb.move(200, 140)

        self.c = QLabel(self)
        self.c.setFont(QFont('TimesNewRoman', 12))
        self.c.setText('Сторона c:')
        self.c.move(50, 160)

        self.inputc = QLineEdit(self)
        self.inputc.move(200, 160)

        self.R = QLabel(self)
        self.R.setText('Радиус описанной окружности:')
        self.R.setFont(QFont('TimesNewRoman', 15))
        self.R.move(100, 200)

        self.LCD_count = QLCDNumber(self)
        self.LCD_count.move(300, 235)

        self.btn1 = QPushButton('Вычислить', self)
        self.btn1.resize(100, 100)
        self.btn1.move(400, 95)
        self.btn1.clicked.connect(self.run)

        self.error = QLabel(self)
        self.error.setFont(QFont('TimesNewRoman', 20))
        self.error.setText('Введены неверные данные')
        self.error.move(3000, 1000)

    def run(self):
        self.error.move(3000, 1000)
        try:
            a = float(self.inputa.text())
            b = float(self.inputb.text())
            c = float(self.inputc.text())
            p = (a + b + c) / 2

            self.LCD_count.display(a * b * c / (4 * (p * (p - a) * (p - b) * (p - c)) ** 0.5))
        except Exception:
            self.error.move(120, 260)