How to use Jython (Robot) to get a pixel color in R,G,B format and then convert it to HEX.
This is my code so far.
import sys
import os
import java.awt.Robot
import java.awt.Color
def get_pixels(posX, posY):
robot = Robot()
Color = getPixelColor(posX, posY)
r = color.getRed()
g = color.getGreen()
b = color.getBlue()
color = "#{:02x}{:02x}{:02x}".format(r,g,b)
return Color
get_pixels(200, 300)
Well, i found out how to make it work, am gonna share my code anyways.
#Jython
import sys
import os
from java.awt import Robot, Color
def get_pixels(posX, posY):
robot = Robot()
colors = robot.getPixelColor(posX, posY)
r = colors.getRed()
g = colors.getGreen()
b = colors.getBlue()
colors = "#{:02x}{:02x}{:02x}".format(r,g,b)
print (colors)
get_pixels(500, 500)
Thanks, regards!
Related
I want to draw a bar chart and a line chart in a view,But In Qt I don't know how to draw them together.Can someone know how to do? thanks.
The code
import os
os.environ["QT_API"] = "pyside6"
from qtpy.QtCharts import *
from qtpy.QtWidgets import *
from qtpy.QtCore import Qt
class View(QChartView):
def __init__(self):
super().__init__()
s1 = QBarSet("W01")
s1.append(200)
s2 = QBarSet("W02")
s2.append(300)
s3 = QBarSet("W03")
s3.append(150)
series = QBarSeries()
series.append([s1, s2, s3])
self._chart = QChart()
self.setChart(self._chart)
self._chart.setTitle("Demo")
self._chart.setAnimationOptions(QChart.SeriesAnimations)
self._chart.addSeries(series)
cats = QBarCategoryAxis()
cats.append(["W01", "W02", "W03"])
self._chart.addAxis(cats, Qt.AlignBottom)
series.attachAxis(cats)
vs = QValueAxis()
vs.setRange(0, 400)
self._chart.addAxis(vs, Qt.AlignLeft)
series.attachAxis(vs)
# line series
line_s = QLineSeries()
### how to set x position as a label is a problem?
line_s.append(0 , 140)
line_s.append(1, 200)
line_s.append(3, 450)
line_s.setPointsVisible(True)
self._chart.addSeries(line_s)
app = QApplication()
view = View()
view.show()
app.exec()
Result
That is not I wanted, I wanted like bellow
So how can I re-write my demo code will be like this?
I want to have the output of the size widget determine the number of widgets created in the output of the return_widgets function. The code below works to a point, but does not update when the value of the intslider changes.
import ipywidgets as widgets
def return_widgets(size):
return [widgets.IntText(value=x) for x in range(size)]
size = widgets.IntSlider(value=3, min=0, max=5, step=1, description='size:')
w = return_widgets(size.value)
widgets.VBox([size, *w])
I did this, not sure it's a very good solution but kind of works:
import ipywidgets as widgets
from IPython.display import display
def return_widgets(size):
return [widgets.IntText(value=x) for x in range(size)]
out = widgets.Output()
def on_value_change(change):
out.clear_output()
with out:
w = return_widgets(change['new'])
display(*w)
size = widgets.IntText(value=3, min=1, max=5, description='size')
size.observe(on_value_change, 'value')
widgets.VBox([size, out])
I want a text that flashes with a clock's seconds. This Link was helpful, but couldn't solve my problem. Below is my little working code:
from tkinter import *
from datetime import datetime
import datetime as dt
import time
def change_color():
curtime=''
newtime = time.strftime('%H:%M:%S')
if newtime != curtime:
curtime = dt.date.today().strftime("%B")[:3]+", "+dt.datetime.now().strftime("%d")+"\n"+newtime
clock.config(text=curtime)
clock.after(200, change_color)
flash_colours=('black', 'red')
for i in range(0, len(flash_colours)):
print("{0}".format(flash_colours[i]))
flashing_text.config(foreground="{0}".format(flash_colours[i]))
root = Tk()
clock = Label(root, text="clock")
clock.pack()
flashing_text = Label(root, text="Flashing text")
flashing_text.pack()
change_color()
root.mainloop()
This line of code: print("{0}".format(flash_colours[i])) prints the alternating colors on the console as the function calls itself every 200s. But the flashing_text Label's text foreground doesn't change colors.
Does anybody have a solution to this problem? Thanks!
Please forgive my bad coding.
Although you have changed the color of the flashing_text in the for loop twice, but the tkinter event handler (mainloop()) can only process the changes when it takes back the control after change_color() completed. So you can only see the flashing_text in red (the last color change).
To achieve the goal, you need to change the color once in the change_color(). Below is a modified change_color():
def change_color(color_idx=0, pasttime=None):
newtime = time.strftime('%H:%M:%S')
if newtime != pasttime:
curtime = dt.date.today().strftime("%B")[:3]+", "+dt.datetime.now().strftime("%d")+"\n"+newtime
clock.config(text=curtime)
flash_colors = ('black', 'red')
flashing_text.config(foreground=flash_colors[color_idx])
clock.after(200, change_color, 1-color_idx, newtime)
I would add it to a class so you can share your variables from each callback.
So something like this.
from tkinter import *
from datetime import datetime
import datetime as dt
import time
class Clock:
def __init__(self, colors):
self.root = Tk()
self.clock = Label(self.root, text="clock")
self.clock.pack()
self.flashing_text = Label(self.root, text="Flashing text")
self.flashing_text.pack()
self.curtime = time.strftime('%H:%M:%S')
self.flash_colours = colors
self.current_colour = 0
self.change_color()
self.root.mainloop()
def change_color(self):
self.newtime = time.strftime('%H:%M:%S')
if self.newtime != self.curtime:
if not self.current_colour:
self.current_colour = 1
else:
self.current_colour = 0
self.curtime = time.strftime('%H:%M:%S')
self.flashing_text.config(foreground="{0}".format(self.flash_colours[self.current_colour]))
self.clock.config(text=self.curtime)
self.clock.after(200, self.change_color)
if __name__ == '__main__':
clock = Clock(('black', 'red'))
Is there an equivalent way in Bokeh to Basemap's drawmapboundary where you can specify certain colors? See the first example here:
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
# setup Lambert Conformal basemap.
m = Basemap(width=12000000,height=9000000,projection='lcc',
resolution='c',lat_1=45.,lat_2=55,lat_0=50,lon_0=-107.)
# draw coastlines.
m.drawcoastlines()
# draw a boundary around the map, fill the background.
# this background will end up being the ocean color, since
# the continents will be drawn on top.
m.drawmapboundary(fill_color='aqua')
# fill continents, set lake color same as ocean color.
m.fillcontinents(color='coral',lake_color='aqua')
plt.show()
I would like to fill waterbodies (e.g., oceans) with the color "aqua". I'm able to generate a black-and-white world map, but how do I color oceans specifically?
I'm using the JSON file for countries from here, and then loading it with GeoJSONDataSource.
import bokeh.plotting as bkp
import bokeh.models as bkm
filename = "test.html"
tools = "pan,wheel_zoom,box_zoom,reset,previewsave"
with open("./countries.geo.json", "r") as f:
countries = bkm.GeoJSONDataSource(geojson=f.read())
p = bkp.figure(width=1000, height=600, tools=tools, title='World Countries', x_axis_label='Longitude', y_axis_label='Latitude')
p.x_range = bkm.Range1d(start=-180, end=180)
p.y_range = bkm.Range1d(start=-90, end=90)
p.patches("xs", "ys", color="white", line_color="black", source=countries)
bkp.output_file(filename)
bkp.save(p, filename)
Figured out by looking at what drawmapboundary does. Just need to set the background color. :)
import bokeh.plotting as bkp
import bokeh.models as bkm
filename = "test.html"
tools = "pan,wheel_zoom,box_zoom,reset,previewsave"
with open("./countries.geo.json", "r") as f:
countries = bkm.GeoJSONDataSource(geojson=f.read())
p = bkp.figure(width=1000, height=600, tools=tools, title='World Countries', x_axis_label='Longitude', y_axis_label='Latitude')
p.background_fill_color = "aqua"
p.x_range = bkm.Range1d(start=-180, end=180)
p.y_range = bkm.Range1d(start=-90, end=90)
p.patches("xs", "ys", color="white", line_color="black", source=countries)
bkp.output_file(filename)
bkp.save(p, filename)
I want to click on the loaded models and move them around. I used the code from chess sample examples and panda 3d tutorial without any success. Can someone figure out whats wrong with the code.
Thanks
from math import pi, sin, cos
import sys
from direct.showbase.ShowBase import ShowBase
import direct.directbase.DirectStart
from direct.task import Task
from panda3d.core import TextNode
from direct.gui.OnscreenText import OnscreenText
from panda3d.core import CollisionTraverser, CollisionNode
from panda3d.core import CollisionHandlerQueue, CollisionRay
from panda3d.core import Point3, Vec3, Vec4, BitMask32
from direct.showbase.DirectObject import DirectObject
from panda3d.core import AmbientLight, DirectionalLight, LightAttrib
class MyApp(ShowBase):
def __init__(self):
ShowBase.__init__(self)
# quit when esc is pressed
self.accept('escape', sys.exit)
#base.disableMouse()
# load the box model
self.box = self.loader.loadModel("models/xbox")
self.box.reparentTo(camera)
self.box.setScale(2.0, 2.0, 2.0)
self.box.setPos(8, 50, 0)
self.keyMap = {
"w" :False ,
"s" :False,
"a": False,
"d": False,
"mouse1": False,
"mouse3": False,
}
# CollisionTraverser and a Collision Handler is set up
self.picker = CollisionTraverser()
self.pq = CollisionHandlerQueue()
self.pickerNode = CollisionNode('mouseRay')
self.pickerNP = camera.attachNewNode(self.pickerNode)
self.pickerNode.setFromCollideMask(BitMask32.bit(1))
self.box.setCollideMask(BitMask32.bit(1))
self.pickerRay = CollisionRay()
self.pickerNode.addSolid(self.pickerRay)
self.picker.addCollider(self.pickerNP, self.pq)
self.mouseTask = taskMgr.add(self.mouseTask, 'mouseTask')
self.accept("mouse1", self.setKey, ["mouse1", True])
def mouseTask(self,task):
# check if we have access to the mouse
if base.mouseWatcherNode.hasMouse():
# get the mouse position
mpos = base.mouseWatcherNode.getMouse()
# set the position of the ray based on the mouse position
self.pickerRay.setFromLens(base.camNode, mpos.getX(), mpos.getY())
self.picker.traverse(render)
# if we have hit something sort the hits so that the closest is first and highlight the node
if self.pq.getNumEntries() > 0:
self.pq.sortEntries()
pickedObj = self.picker.getEntry(0).getIntoNodePath()
def setKey(self,key,value):
self.keyMap[key] = value
app = MyApp()
app.run()
I was just trying to do the same thing, when I found your question.
Thanks for your code, it help me to start!
I've manage to get it working :)
Just a remark: you use a task, with no return, this make the task run once.
You should have used: return task.cont
Anyway, here my working code for panda3d devel (1.8.0+):
import sys
from direct.showbase.ShowBase import ShowBase
from pandac.PandaModules import *
class MyApp(ShowBase):
def __init__(self):
ShowBase.__init__(self)
# quit when esc is pressed
self.accept('escape',sys.exit)
#base.disableMouse()
# load the box model
box = self.loader.loadModel("models/box")
box.reparentTo(render)
box.setScale(2.0, 2.0, 2.0)
box.setPos(8, 50, 0)
panda = base.loader.loadModel("models/panda")
panda.reparentTo(render)
panda.setPos(0, 10, 0)
panda.setScale(0.1, 0.1, 0.1)
cNodePanda = panda.attachNewNode(CollisionNode('cnode_panda'))
cNodePanda.node().addSolid(CollisionSphere(0,0,5,5))
cNodePanda.show()
# CollisionTraverser and a Collision Handler is set up
self.picker = CollisionTraverser()
self.picker.showCollisions(render)
self.pq = CollisionHandlerQueue()
self.pickerNode = CollisionNode('mouseRay')
self.pickerNP = camera.attachNewNode(self.pickerNode)
self.pickerNode.setFromCollideMask(BitMask32.bit(1))
box.setCollideMask(BitMask32.bit(1))
panda.setCollideMask(BitMask32.bit(1))
self.pickerRay = CollisionRay()
self.pickerNode.addSolid(self.pickerRay)
self.picker.addCollider(self.pickerNP,self.pq)
self.accept("mouse1",self.mouseClick)
def mouseClick(self):
print('mouse click')
# check if we have access to the mouse
if base.mouseWatcherNode.hasMouse():
# get the mouse position
mpos = base.mouseWatcherNode.getMouse()
# set the position of the ray based on the mouse position
self.pickerRay.setFromLens(base.camNode,mpos.getX(),mpos.getY())
self.picker.traverse(render)
# if we have hit something sort the hits so that the closest is first and highlight the node
if self.pq.getNumEntries() > 0:
self.pq.sortEntries()
pickedObj = self.pq.getEntry(0).getIntoNodePath()
print('click on ' + pickedObj.getName())
app = MyApp()
app.run()