- Пишем графическую программу на Python с tkinter
- Random Color (RGB) Generator GUI App Using Tkinter in Python
- Python Code to Generate Random Color GUI App using Tkinter.
- 7 Ways to Generate Random Color in Python
- What is a random() Module?
- Generating Random Color in Python Using random() Function in RGB Format
- Generating Random Color in Python Using Random Function in Hexadecimal Format
- Generating Random Color Using NumPy Library
- Generating Random color Using Matplotlib Library
- How to Generate a List of 50 Random Colors in Python?
- Making Random Colors in Python Using Turtle Module
- Generating Random Color Palette Using Seaborn
- Frequently Asked Questions Related to Generating Colors in Python
- Conclusion
Пишем графическую программу на Python с tkinter
В работе со студентами и учениками я заметила, что при изучении какого-либо языка программирования большой интерес вызывает работа с графикой. Даже те студенты, которые скучали на заданиях про числа Фибоначчи, и уже казалось бы у них пропадал интерес к изучению языка, активизировались на темах, связанных с графикой.
Поэтому предлагаю потренироваться в написании небольшой графической програмки на Python с использованием tkinter (кроссплатформенная библиотека для разработки графического интерфейса на языке Python).
Код в этой статье написан для Python 3.5.
Задание: написание программы для рисования на холсте произвольного размера кругов разных цветов.
Не сложно, возможно программа «детская», но я думаю, для яркой иллюстрации того, что может tkinter самое оно.
Хочу рассказать сначала о том, как указать цвет. Конечно удобным для компьютера способом. Для этого в tkinter есть специальный инструмент, который можно запустить таким образом:
from tkinter import * window = Tk() colorchooser.askcolor()
- rom tkinter import * — импорт библиотеки, вернее всех ее методов, на что указывает звездочка (*);
- window = Tk() — создание окна tkinter;
- colorchooser.askcolor() — открывает окно выбора цвета и возвращает кортеж из двух значений: кортеж из трех элементов, интенсивность каждой RGB цвета, и строка. цвет в шестнадцатиричной системе.
Примечание: как сказано в коментариях ниже — звёздочка не все импортирует, надёжнее будет написать
from tkinter import colorchooser
Можно для определения цвета рисования использовать английские название цветов. Здесь хочу заметить, что не все они поддерживаются. Тут говорится, что без проблем вы можете использовать цвета «white», «black», «red», «green», «blue», «cyan», «yellow», «magenta». Но я все таки поэкспериментировала, и вы увидите дальше, что из этого вышло.
Для того, чтобы рисовать в Python необходимо создать холст. Для рисования используется система координат х и у, где точка (0, 0) находится в верхнем левом углу.
В общем хватит вступлений — начнем.
from random import * from tkinter import * size = 600 root = Tk() canvas = Canvas(root, width=size, height=size) canvas.pack() diapason = 0
- from random import * — импорт всех методов модуля random;
- from tkinter import * — это вы уже знаете;
- переменная size понадобится потом;
- root = Tk() — создаем окно;
- canvas = Canvas(root, width=size, height=size) — создаем холст, используя значение переменной size (вот она и понадобилась);
- canvas.pack() — указание расположить холст внутри окна;
- переменная diapason понадобится потом для использования в условии цикла.
colors = choice(['aqua', 'blue', 'fuchsia', 'green', 'maroon', 'orange', 'pink', 'purple', 'red','yellow', 'violet', 'indigo', 'chartreuse', 'lime', ''#f55c4b''])
Создаем список для якобы случайного выбора цвета кругов. Заметьте, что один из цветов написан в формате »#f55c4b» — код цвета в шестнадцатиричной системе.
Здесь хочу остановиться на выборе цвета. Мне хотелось добавить как можно больше вариантов выбора цвета, поэтому я воспользовалась таблицей названий цветов в английском языке. Но вскоре поняла, что многие английские названия не поддерживаются — программа переставала работать. Поэтому определение цвета в шестнадцатиричной системе будет для этих целей более подходящим вариантом.
x0 = randint(0, size) и y0 = randint(0, size) — случайный выбор координат х и у в рамках холста размером size.
d randint(0, size/5) — произвольный выбор размера круга, ограниченный size/5.
canvas.create_oval(x0, y0, x0+d, y0+d, fill=colors) — собственно говоря рисуем круги, в точках с координатами x0 и y0, размерами по вертикали и горизонтали x0+d и y0+d, заливкой цветом, который выбирается случайным образом из списка colors.
root.update() — update() — обрабатывает все задачи, стоящие в очереди. Обычно эта функция используется во время «тяжёлых» расчётов, когда необходимо чтобы приложение оставалось отзывчивым на действия пользователя.
Без этого в итоге отобразятся круги, но процесс их появления будет вам не виден. А именно это придает шарм этой програмке.
diapason += 1 — шаг цикла, счетчик.
В результате получается такая картинка:
Мне не понравилось, что справа и вверху какие-то пустые места образовываются, поэтому я немного изменила условие цикла while diapason < 2000 или 3000. Так холст получился более заполненным.
Также можно сделать цикл бесконечным:
while True: colors = choicecolors = choice(['aqua', 'blue', 'fuchsia', 'green', 'maroon', 'orange', 'pink', 'purple', 'red','yellow', 'violet', 'indigo', 'chartreuse', 'lime']) x0 = randint(0, size) y0 = randint(0, size) d = randint(0, size/5) canvas.create_oval(x0, y0, x0+d, y0+d, fill=colors ) root.update()
Я думаю, можно было бы еще поиграться со скоростью рисования кругов или их движением по холсту. Можно было увеличить варианты выбора цветов. Поставить условие для остановки бесконечного цикла, например по нажатию пробела. Это все задания для будущих программ.
Студенты еще спросили, а можно ли запускать это как заставку на рабочем столе Windows? Пока не нашла как это можно было бы сделать.
Random Color (RGB) Generator GUI App Using Tkinter in Python
In this tutorial let’s write Python Script to create Random Color (RGB) Generator GUI App Using Tkinter in Python.
Python Code to Generate Random Color GUI App using Tkinter.
Tkinter is a Python library that allows you to create GUI (Graphical User Interface) applications by using a variety of widgets and methods. It supports images, just like any other GUI module, so you may use them to spice up your program.
Using Python, I built a random color generator with preview within tkinter. The application’s whole source code is provided below.
128: textcolor = '#000000' else: textcolor = '#ffffff' self.itemconfigure(self.__t, text=colorstring, fill=textcolor) def setRed(self, event=None): if self.__redScale: self.__red = self.__redScale.get() colorstring = '#%s%s%s' % (self.toHex(self.__red), self.toHex(self.__green), self.toHex(self.__blue)) self.configure(background=colorstring) self.showHexColor(colorstring) def setGreen(self, event=None): if self.__greenScale: self.__green = self.__greenScale.get() colorstring = '#%s%s%s' % (self.toHex(self.__red), self.toHex(self.__green), self.toHex(self.__blue)) self.configure(background=colorstring) self.showHexColor(colorstring) def setBlue(self, event=None): if self.__blueScale: self.__blue = self.__blueScale.get() colorstring = '#%s%s%s' % (self.toHex(self.__red), self.toHex(self.__green), self.toHex(self.__blue)) self.configure(background=colorstring) self.showHexColor(colorstring) main()
To execute the code through command line, you can use python3 app.py
Similar Posts:
7 Ways to Generate Random Color in Python
Now we are going to see how to generate random colors using Python. We are going to generate colors in two formats. One is RGB format, and the other is hexadecimal format. In this digital world, we are using that two formats highly. Generally, colors are represented in different formats. We can generate color using python libraries such as Numpy, Matplotlib, and turtle.
RGB represents Red, Green, and Blue. It has an integer value from 0 to 255. The combination of these three colors gives many colors. The hexadecimal format starts with the #sign, followed by six hexadecimal digits. The hexadecimal colors are Red, Green, and Blue. We are using a random() module to generate a random color.
What is a random() Module?
random() is a module that is useful to generate random integers or colors in python. This is a built-in module in python. It is useful to select things randomly, and it is also useful to shuffle the things in the list.
Generating Random Color in Python Using random() Function in RGB Format
import random r = random.randint(0,255) g = random.randint(0,255) b = random.randint(0,255) rgb = [r,g,b] print('A Random color is :',rgb)
Explanation
First, importing a random function to get the random color in python. A variables r is for red color, g is for green, and b is for blue color. We know that the RGB format has an integer value from 0 to 255. So we are giving the range as 0 to 255. It will take any value from the range. random.randint() is a method to give the range.
A Random color is : [172, 68, 77]
Generating Random Color in Python Using Random Function in Hexadecimal Format
import random hexadecimal = ["#"+''.join([random.choice('ABCDEF0123456789') for i in range(6)])] print("A Random color is :",hexadecimal)
Explanation
First, importing a random module to generate the random color in hexadecimal format . And then using the join() function to join the # and color code. Color code will always start with #. Using for loop to iterate. Now the color code is generated.
A Random color is : ['#1E8D5C']
Generating Random Color Using NumPy Library
import numpy as np random_color=list(np.random.choice(range(255),size=3)) print("A Random color is:",random_color)
Explanation
First importing Numpy library as np. Next assigning a value and size of the color in a variable random_color. The color will display in the list because we declared it as a list—next, printing random_color.
A Random color is: [64, 217, 111]
Generating Random color Using Matplotlib Library
import matplotlib.pyplot as plt import random no_of_colors=5 color=["#"+''.join([random.choice('0123456789ABCDEF') for i in range(6)]) for j in range(no_of_colors)] print(color) for j in range(no_of_colors): plt.scatter(random.randint(0,10),random.randint(0,10),c=color[j],s=200) plt.show()
Explanation
First importing matplotlib library. Next, importing a random module. Next, assign a value in a variable named no_of_colors. And then using the join() function to join the # and color code. Color code will always start with #. Using for loop to iterate. Now the color code is generated. The color will display in the list because we declared it as a list—next, printing random_color.
['#4EC62C', '#DD382B', '#EB700E', '#4100C8', '#DBDA94']
How to Generate a List of 50 Random Colors in Python?
import random for j in range(50): rand_colors = ["#"+''.join([random.choice('ABCDEF0123456789') for i in range(6)])] print(rand_colors)
Explanation
First, importing a random module to get the random colors. Next to creating a for loop to iterate 50 times to get 50 different colors. And then using the join() function to join the # and color code. Color code will always start with #. Using for loop to iterate. Now the color codes are generated.
['#B74E09'] ['#61B22E'] ['#4B2DF7'] ['#5EB999'] ['#5DBDE7'] ['#DD629B'] ['#B2A6A3'] ['#C9212C'] ['#E63DC4'] ['#A13C50'] ['#4E4327'] ['#76A9CA'] ['#DD7C03'] ['#80D077'] ['#48A6B8'] ['#AC9FA1'] ['#D84CE4'] ['#D6FE6E'] ['#D67956'] ['#158AA4'] ['#A7D400'] ['#381902'] ['#6AD714'] ['#0FBA51'] ['#EF274A'] ['#9E6D0A'] ['#578C79'] ['#990B61'] ['#E4BB06'] ['#F57ADD'] ['#FB8136'] ['#1DEEF5'] ['#BB34C2'] ['#89FEAC'] ['#49577E'] ['#E9BB2A'] ['#4EFF67'] ['#A262DF'] ['#8BB529'] ['#3D714E'] ['#DAEB9D'] ['#A1B35B'] ['#31F277'] ['#A43B68'] ['#1E7DB8'] ['#81BBA2'] ['#6B1CAA'] ['#24F932'] ['#757B02'] ['#7415F6']
Making Random Colors in Python Using Turtle Module
from turtle import * from random import randint speed(0) pensize(5) colormode(255) while True: color(randint(0, 255), randint(0, 255), randint(0, 255)) begin_fill() circle(10) end_fill() penup() goto(randint(-300, 300), randint(-200, 170)) pendown()
From turtle library importing star. From random module importing randint. Declaring pensize, speed, and colormode(). Colormode is 255 so that it will show all the colors. Color will be displayed till the condition becomes false. Using begin_fill to start filling the color. The size of the circle is 10. using end_fill to end filling the color. Using penup() to start drawing and pendown() to stop drawing.
Generating Random Color Palette Using Seaborn
import seaborn as sns palette = sns.color_palette(None, 3) print(palette)
First importing seaborn library. A variable palette is holding the color_palette. Next, printing the palette.
[(0.12156862745098039, 0.4666666666666667, 0.7058823529411765), (1.0, 0.4980392156862745, 0.054901960784313725), (0.17254901960784313, 0.6274509803921569, 0.17254901960784313)]
Frequently Asked Questions Related to Generating Colors in Python
The random() module is used to generate random colors in python.
RGB format and hexadecimal format are the formats to generate the color.
Numpy, Matplotlib, and turtle are the libraries useful to generate colors randomly.
Conclusion
Here we have seen about generating random colors in python. We have used a lot of methods and formats to generate colors. These are the methods that are available to generate random colors.