Tkinter colorchooser problems
02 May, 2013
My son has found a problem. It is regarding:
from tkinter import *
colorchooser.askcolor()
It is not working and I cannot help him. On the python shell he gets an error:
Traceback (most recent call last):
File «colorrect.py», line 2, in
colorchooser.askcolor()
NameError: name ‘colorchooser’ is not defined
This is an odd one. If I try the code in the Shell, the color chooser is available as expected:
But if I try the same code in the command-line console, I get a similar error:
The only way I can reproduce the problem in the Shell is when I don’t run it in «No Subprocess» mode — that’s if you don’t follow the installation instructions, in Chapter 1 of the book, and just run the Shell/IDLE as it was installed (without modifying the shortcut):
You can get around this, by directly importing the colorchooser module like so:
But you’ll probably hit problems if you try to call the askcolor function (the second line in that snippet of code above).
All of which is rather messy and confusing. My suggestion would be to make sure you see the «No Subprocess» message when you run IDLE, and if not, revisit Chapter 1. If you do see the message on startup, and still get the error (which I haven’t managed to do, but I’m guessing might be possible), try the sample code above, and see if that works for you. Good luck!
More information updated July 2020 here.
Источник
Пишем графическую программу на Python с tkinter
В работе со студентами и учениками я заметила, что при изучении какого-либо языка программирования большой интерес вызывает работа с графикой. Даже те студенты, которые скучали на заданиях про числа Фибоначчи, и уже казалось бы у них пропадал интерес к изучению языка, активизировались на темах, связанных с графикой.
Поэтому предлагаю потренироваться в написании небольшой графической програмки на Python с использованием tkinter (кроссплатформенная библиотека для разработки графического интерфейса на языке Python).
Код в этой статье написан для Python 3.5.
Задание: написание программы для рисования на холсте произвольного размера кругов разных цветов.
Не сложно, возможно программа «детская», но я думаю, для яркой иллюстрации того, что может tkinter самое оно.
Хочу рассказать сначала о том, как указать цвет. Конечно удобным для компьютера способом. Для этого в tkinter есть специальный инструмент, который можно запустить таким образом:
Пояснения к коду:
- 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 * — импорт всех методов модуля random;
- from tkinter import * — это вы уже знаете;
- переменная size понадобиться потом;
- root = Tk() — создаем окно;
- canvas = Canvas(root, width=size, height=size) — создаем холст, используя значение переменной size (вот она и понадобилась);
- canvas.pack() — указание расположить холст внутри окна;
- переменная diapason понадобиться потом для использования в условии цикла.
Дальше создаем цикл:
Пояснения к коду:
- while diapason
Источник
Tkinter Color Chooser
This section covers the color chooser module in Tkinter.
Tkinter is full of mini libraries that offer new and interesting features, improving the overall look and feel of your Python GUI. One of these many Tkinter Libraries is the Color Chooser.
You can import the askcolor function from the Color Chooser library using the following code.
The syntax for the askcolor function is as follows. All parameters on this function or optional. You can assign it a default color and a title, but you can also leave both of these out.
The look of this Color Chooser can vary from operating system to operating system, but the general purpose and functionality remains the same.
Color Chooser Example
Below is a standard example of the askcolor function, without the supporting tkinter window.
Any color you pick will return a tuple as it’s value. There are two values contained in this tuple. The first is a RGB representation and the second is a hexadecimal value. We’ll be needing the hexadecimal value for tkinter.
We picked a random color using the code above. See it’s output below.
Extra Tkinter Example
Here’s an extra example of the use of the Color Chooser’s askcolor function. This is the kind of example you’ll see in real life, where the user selects a color, and the font color on the GUI changes accordingly.
We’ve run the function, and picked the color blue from the color palette. You can now see that the color of the text in the label has been changed.
This marks the end of the Tkinter Color Chooser Article. Suggestions or contributions for CodersLegacy are more than welcome. Any questions can be directed to the comments section below.
To see other tkinter related tit bits, head over to the Python problem solving page and scroll down to the Tkinter section.
Источник
Tkinter Color Chooser
Summary: in this tutorial, you’ll learn how to display a color chooser dialog using the askcolor() function from the tkinter.colorchooser module.
Introduction to the Tkinter color chooser dialog
To display a native color chooser dialog, you use the tkinter.colorchooser module.
First, import the askcolor() function from the tkinter.colorchooser module:
Second, call the askcolor() function to display the color chooser dialog:
If you select a color, the askcolor() function returns a tuple that contains two values that represent the selected color:
- The first value is the RGB representation.
- The second value is a hexadecimal representation.
If you don’t select any color from the color chooser dialog, the askcolor() function returns None .
Tkinter color chooser example
The following program illustrates how to use the color chooser dialog. The background of the root window will change to the selected color.
First, import the tkinter and tkinter.colorchooser modules:
Second, create the root window:
Third, define a function that will be executed when the ‘Select a Color’ Button is clicked:
Fourth, create a button and assign the change_color() function to its command option:
Finally, run the mainloop() method of the root window:
Источник
Функция выбора цвета
У меня есть небольшая программа, которая на поле canvas рисует разные фигуры. Когда нажимаешь на кнопки «Выбор заливки» и «Выбор обводки» открывается окно выбора цвета. Так вот, как сделать чтобы выбранные цвета использовались при нарисовке фигуры? У меня никак не получается.
Помощь в написании контрольных, курсовых и дипломных работ здесь.
Диалоги выбора цвета и шрифта — получение результата выбора
Имеем функцию Function FUN_OPEN_FONT() As String ‘ диалог выбора ЦВЕТА ‘.
Нужна задачка выбора названия цвета в ComboBox и последующего появления самого цвета в другом окне
Выбираешь название цвета (red,black и т.д) в ComboBox и чтобы сам цвет появлялся в другом окне.
ContextMenu изменение цвета выбора и цвета текста
Добрый день подскажите как сделать так что бы после выбора пункта меню цвет текста менялся обратно.
Как создать диалог выбора шрифта и диалог выбора цвета
как создать диалог выбора шрифта и диалог выбора цвета в wpf
Решение
Палитра выбора цвета
есть ли в wpf что-то вроде объекта, как в WinForms — ColorDialog м? или как можно организовать.
Меню выбора цвета
Нашёл программу на С++ (исходник рабочий), С++ я не знаю. https://yadi.sk/d/LMbvXOKGrrYbZ Хочу.
UserControl выбора цвета
Здравствуйте! Помогите пожалуйста написать вот такой UserControl для WindowsForms!
Окно выбора цвета
Здравствуйте! Подскажите, есть ли в WinApi стандортное окно выбора цвета и как им воспользоваться?
Стандартное окно выбора цвета
есть у кого нибудь исходник этого ? Буду очень признателен.
comboBox для выбора цвета
как мне сделать comboBox так что бы я при выбора цвета менялся цвет формы?, Заранее Спасибо:)
Источник