В wx python создадим кнопку клавиатуры для интерфейса ATM.сделать вывод, депозит на сохранение.При нажатии кнопки текст должен отображаться в текстовом поле. - PullRequest
0 голосов
/ 18 апреля 2019

. Пример кодов ниже: import wx

btn_list = ['7', '8', '9', '*', 'C', '4', '5', '6', '/', 'M->', '1', '2', '3', '-', '-> M', '0', '.', '=', '+', 'neg ']

но не знаю, как получить кнопку в таком формате, как клавиатура

, как связать поле ввода с клавиатурой.я должен выглядеть, чтобы сделать это так ... entry.insert ('end', btn)

1 Ответ

0 голосов
/ 18 апреля 2019

Я не могу вспомнить, откуда появился этот код, но он находился в моем каталоге ответов StackOverflow в течение 2 лет, так что, возможно, в какой-то момент я его смоделировал или, может быть, я его где-то ущипнул.
Это не ответ на ваш вопрос, потому что, честно говоря, это не так уж и много, но это может помочь вам с wx.GridSizer, который вы собираетесь использовать.

from __future__ import division
import wx
from math import * 
from cmath import pi

class Calculator(wx.Panel):
    '''Main calculator dialog'''
    def __init__(self, *args, **kwargs):
        wx.Panel.__init__(self, *args, **kwargs)
        sizer = wx.BoxSizer(wx.VERTICAL) # Main vertical sizer

        self.display = wx.ComboBox(self) # Current calculation
        sizer.Add(self.display, 0, wx.EXPAND|wx.BOTTOM, 8) # Add to main sizer

        gsizer = wx.GridSizer(9,4, 8, 8)
        for row in (("(",")","x^y","root"),
                    ("sin","cos","tan","e^x"),
                    ("arcsin","arccos","arctan","Pi"),
                    ("sinh","cosh","tanh","e"),
                    ("arcsinh","arccosh","arctanh","n!"),
                    ("7", "8", "9", "/"),
                    ("4", "5", "6", "*"),
                    ("1", "2", "3", "-"),
                    ("0", ".", "C", "+")):
            for label in row:
                b = wx.Button(self, label=label, size=(50,-1))
                gsizer.Add(b)
                b.Bind(wx.EVT_BUTTON, self.OnButton)
        sizer.Add(gsizer, 1, wx.EXPAND)

        # [    =     ]
        b = wx.Button(self, label="=")
        b.Bind(wx.EVT_BUTTON, self.OnButton)
        sizer.Add(b, 0, wx.EXPAND|wx.ALL, 8)
        self.equal = b

        # Set sizer and center
        self.SetSizerAndFit(sizer)

    def OnButton(self, evt):
        '''Handle button click event'''

        # Get title of clicked button
        label = evt.GetEventObject().GetLabel()

        if label == "=": # Calculate
            self.Calculate()

        elif label == "C": # Clear
            self.display.SetValue("")
        elif label == "x^y":
 #           self.display.SetValue("pow(x,y)")
            self.display.SetValue(self.display.GetValue() + "^")
        elif label == "x^2":
            self.display.SetValue("pow(x,2)")
        elif label == "10^x":
            self.display.SetValue("pow(10,x)")
        elif label == "e^x":
            self.display.SetValue("exp")
        elif label == "arcsin":
            self.display.SetValue("asin("+self.display.GetValue()+")")
        elif label == "arccos":
            self.display.SetValue("acos")
        elif label == "arcsinh":
            self.display.SetValue("asinh")
        elif label == "arccosh":
            self.display.SetValue("acosh")
        elif label == "arctanh":
            self.display.SetValue("atanh")
        elif label == "arctan":
            self.display.SetValue("atan")
        elif label == "n!":
            self.display.SetValue("factorial")
        elif label == "Pi":
            self.display.SetValue("pi")
        elif label == "root":
            self.display.SetValue("sqrt")



        #x^y,x^2,10^x


        else: # Just add button text to current calculation
            self.display.SetValue(self.display.GetValue() + label)
            self.display.SetInsertionPointEnd()
            self.equal.SetFocus() # Set the [=] button in focus

    def Calculate(self):
        """
        do the calculation itself

        in a separate method, so it can be called outside of a button event handler
        """
        try:
            compute = self.display.GetValue()
            if "^" in compute:
                start, end = compute.split("^")
                compute = "pow("+start+","+end+")"
            # Ignore empty calculation
            if not compute.strip():
                return

            # Calculate result
            result = eval(compute)

            # Add to history
            self.display.Insert(compute, 0)

            # Show result
            self.display.SetValue(str(result))
        except e:
            wx.LogError(str(e))
            return

    def ComputeExpression(self, expression):
        """
        Compute the expression passed in.

        This can be called from another class, module, etc.
        """
        print ("ComputeExpression called with:"), expression
        self.display.SetValue(expression)
        self.Calculate()

class MainFrame(wx.Frame):
    def __init__(self, *args, **kwargs):
        kwargs.setdefault('title', "Calculator")
        wx.Frame.__init__(self, *args, **kwargs)

        self.calcPanel = Calculator(self)

        # put the panel on -- in a sizer to give it some space
        S = wx.BoxSizer(wx.VERTICAL)
        S.Add(self.calcPanel, 1, wx.GROW|wx.ALL, 10)
        self.SetSizerAndFit(S)
        self.CenterOnScreen()


if __name__ == "__main__":
    # Run the application
    app = wx.App(False)
    frame = MainFrame(None)
    frame.Show()
    app.MainLoop()

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...