使用 tkinter 制作简单的计算器 GUI 界面

使用 tkinter 制作简单的计算器 GUI 界面

说明

  • 个人学习阶段的学习成果,为了巩固学习知识,仅仅制作Gui界面,后续添加计算等功能

代码案例

import tkinter as tk


class Appclication(object):
    def __init__(self, master):
        self.master = master
        self.createwidget()

    def createwidget(self):
        var = tk.IntVar()
        entry = tk.Entry(self.master, textvariable=var, bg='white', font=('黑体', 20), width=28)
        entry.grid(row=0, column=0, columnspan=4, sticky='NSEW', pady=8.0, padx=2.5)

        btnText = (('%', 'CE', 'C', '×'),
                   ('1/x', 'x²', '√', '÷'),
                   (7, 8, 9, '×'),
                   (4, 5, 6, '-'),
                   (1, 2, 3, '+'),
                   (0, '.', '='))

        for index1, value1 in enumerate(btnText):
            for index2, value2 in enumerate(value1):
                if value2 == '=':
                    button = tk.Button(self.master, text=value2, activebackground='red')
                    button.grid(row=index1 + 1, column=index2, sticky='NSEW', columnspan=2)
                elif value2 == 'CE':
                    button = tk.Button(self.master, text=value2, state='disabled', activebackground='red')
                    button.grid(row=index1 + 1, column=index2, sticky='NSEW', ipady=8.0, padx=0.4)
                elif value2 == 'C':
                    button = tk.Button(self.master, text=value2, state='disabled', activebackground='red')
                    button.grid(row=index1 + 1, column=index2, sticky='NSEW', ipady=8.0, padx=0.4)
                elif value2 == '1/x':
                    button = tk.Button(self.master, text=value2, state='disabled', activebackground='red')
                    button.grid(row=index1 + 1, column=index2, sticky='NSEW', ipady=8.0, padx=0.4)
                elif value2 == '√':
                    button = tk.Button(self.master, text=value2, state='disabled', activebackground='red')
                    button.grid(row=index1 + 1, column=index2, sticky='NSEW', ipady=8.0, padx=0.4)
                else:
                    button = tk.Button(self.master, text=value2, activebackground='red')
                    button.grid(row=index1 + 1, column=index2, sticky='NSEW', ipady=8.0, padx=0.4)


if __name__ == '__main__':
    root = tk.Tk()
    root.title('计算器')
    root.geometry('400x323+500+200')
    root.resizable(width=False, height=False)
    App = Appclication(root)
    root.mainloop()

效果图

posted @ 2021-04-16 14:46  廿九九  阅读(347)  评论(0)    收藏  举报