📜  python button graphics.py - Python (1)

📅  最后修改于: 2023-12-03 15:04:04.400000             🧑  作者: Mango

Python Button Graphics

The button module in graphics.py is a helpful tool for creating interactive GUIs.

Installation

You can install graphics.py by running the following command in your terminal:

pip install graphics.py
Getting Started

Here is an example code snippet that creates a simple button with graphics.py:

from graphics import *

win = GraphWin("My Button", 200, 100)

button = Rectangle(Point(50, 30), Point(150, 70))
button.setOutline("black")
button.setFill("white")
button.draw(win)

text = Text(button.getCenter(), "Click me!")
text.draw(win)

while True:
    click_point = win.getMouse()
    if button.getP1().getX() < click_point.getX() < button.getP2().getX() and \
       button.getP1().getY() < click_point.getY() < button.getP2().getY():
        button.setFill("gray")
    else:
        button.setFill("white")

The code above first creates a GraphWin object with the title "My Button" and dimensions of 200 x 100 pixels. Then it creates a Rectangle object to form the button, sets the outline color to black, and fills the button with white.

Next, it creates a Text object, positions it at the center of the button, and adds it to the window.

Finally, it enters an infinite loop that waits for the user to click the mouse within the bounds of the button. If the user clicks the button, the button color changes to gray; otherwise, the button color returns to white.

Conclusion

With the button module in graphics.py, you can easily create interactive buttons in your Python GUIs. Just import the graphics module, create a Rectangle object for the button, and add a Text object for the button label. Then use a loop to detect when the user clicks the button and perform whatever action you desire.