Home Backend Development Python Tutorial python计算圆周长、面积、球体体积并画出圆

python计算圆周长、面积、球体体积并画出圆

Jun 06, 2016 am 11:30 AM

输入半径,计算圆的周长、面积、球体体积,并画出这个圆。
拖动条、输入框和图像控件的数据保持一致!

Fedora下测试通过

代码如下:


#https://github.com/RobberPhex/GTK-Example-CalcArea
from gi.repository import Gtk, Gdk, GdkPixbuf
from PIL import Image, ImageDraw
from io import BytesIO
from math import pi

class Model:
    '''
    模型类
    存储半径,计算周长、面积、体积
    '''

    def __init__(self):
        self._radius = 0

    def setRadius(self, radius):
        self._radius = float(radius)

    def getRadius(self):
        return self._radius

    def getPerimeter(self):
        return pi * self._radius * 2

    def getArea(self):
        return self._radius ** 2 * pi

    def getVolume(self):
        return 4 * pi * self._radius ** 3 / 3


class Controller:
    '''
    控制器类
    控制视图和模型的更新
    '''

    def __init__(self, model):
        self.model = model
        self._observers = []

    def addObserver(self, observer):
        self._observers.append(observer)

    def setRadius(self, radius):
        model.setRadius(radius)
        self.notify()

    def notify(self):
        for observer in self._observers:
            observer.update()


class TextView:
    '''
    文字视图类
    处理文本输入框的视图
    '''

    def __init__(self, model, rEntry, pEntry, aEntry, vEntry):
        '''
        :type model Model
        '''
        self.model = model
        self.rEntry = rEntry
        self.pEntry = pEntry
        self.aEntry = aEntry
        self.vEntry = vEntry

    def update(self):
        self.rEntry.set_text('%2.2f' % self.model.getRadius())
        self.pEntry.set_text('%2.2f' % self.model.getPerimeter())
        self.aEntry.set_text('%2.2f' % self.model.getArea())
        self.vEntry.set_text('%2.2f' % self.model.getVolume())


class ScaleView:
    '''
    拖动条视图
    处理拖动条的视图
    '''

    def __init__(self, model, scale):
        '''
        :type model Model
        '''
        self.model = model
        self.scale = scale

    def update(self):
        self.scale.set_value(self.model.getRadius())


class ImageView:
    '''
    图像视图
    处理图像的视图
    '''

    @classmethod
    def imgToPixbuf(cls, img):
        '''
        :type img Image
        '''
        buff = BytesIO()
        img.save(buff, 'ppm')
        contents = buff.getvalue()
        buff.close()

        loader = GdkPixbuf.PixbufLoader.new_with_type('pnm')
        loader.write(contents)
        pixbuf = loader.get_pixbuf()
        loader.close()
        return pixbuf

    @classmethod
    def ellipse(cls, radius):
        '''
        :type radius int
        '''
        image = Image.new("RGBA", (300, 300), "white")
        draw = ImageDraw.Draw(image)
        minor = 150 - radius
        major = 150 + radius
        draw.ellipse((minor, minor, major, major), outline='red')
        pixbuf = ImageView.imgToPixbuf(image)
        return pixbuf

    def __init__(self, model, image):
        self.model = model
        self.image = image

    def update(self):
        radius = self.model.getRadius()
        pixbuf = ImageView.ellipse(radius)
        self.image.set_from_pixbuf(pixbuf)


class MainWindow(Gtk.Window):
    '''
    主窗口类
    负责整体界面的显示
    '''

    def textCallback(self, widget, controller):
        '''
        文本输入回调
        '''
        try:
            radius = float(widget.get_text())
            controller.setRadius(radius)
        except ValueError as e:
            pass

    def scaleCallback(self, widget, controller):
        '''
        拖动条回调
        '''
        radius = widget.get_value()
        controller.setRadius(radius)

    def __init__(self):
        Gtk.Window.__init__(self, title="Title")

        self.set_default_size(600, 400)
        self.set_position(Gtk.WindowPosition.CENTER)

        hbox = Gtk.HBox(spacing=5)
        self.add(hbox)

        vbox = Gtk.VBox(spacing=5)
        hbox.pack_start(vbox, True, True, 2)

        table = Gtk.Table.new(4, 2, False)
        vbox.pack_start(table, True, True, 2)

        label = Gtk.Label('半径:')
        table.attach_defaults(label, 0, 1, 0, 1)
        label = Gtk.Label('周长:')
        table.attach_defaults(label, 0, 1, 1, 2)
        label = Gtk.Label('面积:')
        table.attach_defaults(label, 0, 1, 2, 3)
        label = Gtk.Label('体积:')
        table.attach_defaults(label, 0, 1, 3, 4)

        self.radiusEntry = Gtk.Entry.new()
        self.radiusEntry.connect('changed', self.textCallback, controller)
        table.attach_defaults(self.radiusEntry, 1, 2, 0, 1)
        self.perimeterEntry = Gtk.Entry.new()
        self.perimeterEntry.set_sensitive(False)
        self.perimeterEntry.set_text('周长')
        table.attach_defaults(self.perimeterEntry, 1, 2, 1, 2)
        self.areaEntry = Gtk.Entry.new()
        self.areaEntry.set_sensitive(False)
        self.areaEntry.set_text('面积')
        table.attach_defaults(self.areaEntry, 1, 2, 2, 3)
        self.volumeEntry = Gtk.Entry.new()
        self.volumeEntry.set_sensitive(False)
        self.volumeEntry.set_text('体积')
        table.attach_defaults(self.volumeEntry, 1, 2, 3, 4)

        self.scale = Gtk.HScale.new_with_range(0, 100, 1)
        self.scale.connect('value-changed', self.scaleCallback, controller)
        vbox.pack_start(self.scale, False, False, 2)

        pixbuf = GdkPixbuf.Pixbuf.new(GdkPixbuf.Colorspace.RGB, True, 8, 300, 300)
        pixbuf.fill(0xaaaaaaaa)
        self.image = Gtk.Image.new_from_pixbuf(pixbuf)
        hbox.pack_start(self.image, True, True, 2)

        self.connect('delete-event', Gtk.main_quit)


model = Model()
controller = Controller(model)

if __name__ == '__main__':
    Gdk.threads_init()
    Gdk.threads_enter()
    win = MainWindow()

    iv = ImageView(model, win.image)
    controller.addObserver(iv)

    tv = TextView(model, win.radiusEntry, win.perimeterEntry, win.areaEntry, win.volumeEntry)
    controller.addObserver(tv)

    sv = ScaleView(model, win.scale)
    controller.addObserver(sv)

    win.show_all()
    Gtk.main()
    Gdk.threads_leave()



python计算圆周长、面积、球体体积并画出圆
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

See all articles