how to display the values in Entry in tkinter? - python

I wanted to know how to display the integer and double values in the text box. As I have to calculate mean values of an image, and I want those values to be displayed in the text box in the GUI.
When I tried with my code I got an error:
AttributeError: numpy.ndarray object has no attribute set
This is because I'm using .set() for ndarray. But without .set() how to send the values to the textbox?
Here's my code snippet:
def open():
path=tkFileDialog.askopenfilename(filetypes=[("Image File",'.jpg')])
blue, green, red = cv2.split(re_img)
total = re_img.size
B = sum(blue) / total
G = sum(green) / total
R = sum(red) / total
B_mean1.append(B)
G_mean1.append(G)
R_mean1.append(R)
blue.set(B_mean)
root = Tk()
blue_label = Label(app,text = 'Blue Mean')
blue_label.place(x = 850,y = 140)
blue = IntVar(None)
blue_text = Entry(app,textvariable = blue)
blue_text.place(x = 1000,y = 140)
button = Button(app, text='Select an Image',command = open)
button.pack(padx = 1, pady = 1,anchor='ne')
button.place( x = 650, y = 60)
root.mainloop()
I have no idea whether my coding is wrong or not. And these mean values are being stored in list. Any suggestions for this problem?
Thanks for your support!

blue is a local name in your function, shadowing your global IntVar reference blue.
Rename one or the other.

There's nothing on numpy.ndarray called "set":
http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html
Take a good look at this reference and figure out how to apply B_mean to blue.

Related

Python-PPTX : Data Label Positions not working for Doughnut Chart

I have a Chart Placeholder, into which I have inserted a chart of chart_type 'DOUGHNUT'. I've added data labels to it and want to change their positions. For some reason, the method given in the documentation has no effect on my chart.
Here is my code, please help if I'm doing something wrong -
from pptx import Presentation
from pptx.chart.data import ChartData
from pptx.enum.chart import XL_CHART_TYPE, XL_LABEL_POSITION, XL_DATA_LABEL_POSITION, XL_TICK_MARK, XL_TICK_LABEL_POSITION
chart_data = ChartData()
chart_data.add_series('', tuple(input_chart_data[x] for x in input_chart_data))
graphic_frame = content_placeholder.insert_chart(XL_CHART_TYPE.DOUGHNUT, chart_data)
chart = graphic_frame.chart
chart.has_legend = False
#Adding Data-Labels with custom text
chart.plots[0].has_data_labels = True
data_labels = chart.plots[0].data_labels
i = 0
series = chart.series[0]
for point in series.points:
fill = point.format.fill
fill.solid()
fill.fore_color.rgb = RGBColor(<color_code>)
point.data_label.has_text_frame = True
#Assigning custom text for data label associated with each data-point
point.data_label.text_frame.text = str(chart_data.categories[i].label) + "\n" + str(float(chart.series[0].values[i])) + "%"
for run in point.data_label.text_frame.paragraphs[0].runs:
run.font.size = Pt(10)
i+=1
data_labels.position = XL_LABEL_POSITION.OUTSIDE_END
PowerPoint is finicky about where you place certain chart attributes and feels free to ignore them when it wants (although it does so consistently).
A quick option worth trying is to set the value individually, point-by-point in the series. So something like:
for point in series.points:
point.data_label.position = XL_LABEL_POSITION.OUTSIDE_END
The most reliable method is to start by producing the effect you want by hand, using PowerPoint itself on an example chart, then inspecting the XML PowerPoint produces in the saved file, perhaps using opc-diag. Once you've identified what XML produces the desired effect (or discovered PowerPoint won't let you do it), then you can proceed to working out how to get the XML generated by python-pptx. That might make a good second question if you're able to get that far.
I made it work by writing the below code.
def apply_data_labels(self, chart):
plot = chart.plots[0]
plot.has_data_labels = True
for series in plot.series:
values = series.values
counter = 0
for point in series.points:
data_label = point.data_label
data_label.has_text_frame = True
data_label.text_frame.text = str(values[counter])
counter = counter + 1
the cause of error is setting the label position. no matter what you set it asks to repair the PPT. will have to drill down more to see why is it so.
Also to save some more time the formatting doesn't works(font color, size)
If anybody has any leads then please help.
To add on Vibhanshu's response, I could get the formatting (font type, font color, size etc) to work using the following code:
for idx, point in enumerate(chart.series[0].points):
# set position
point.data_label.position = XL_LABEL_POSITION.OUTSIDE_END
# set text
point.data_label.has_text_frame = True
point.data_label.text_frame.text = "This is an example"
# set formatting
for paragraph_idx, paragraph in enumerate(point.data_label.text_frame.paragraphs):
paragraph.line_spacing = 0.6 # set paragraph line spacing
for run in paragraph.runs:
run.font.size = Pt(30) #set font size
run.font.name = 'Poppins Medium' #set font name
run.font.color.rgb = RGBColor.from_string("FF0000") #set font color

Can't use variables to define color with Pillow

I'm getting stuck on a small (I guess) error using Pillow. I'm trying to set the color of my text with a variable but get a ValueError: unknown color specifier: '"232,43,123,255"' when trying it.
Here is my code :
header = Image.open("A.png")
couleur_Ellipse = "rose"
draw = ImageDraw.Draw(header)
point = ( int(header.width * 0.780), int(header.height * 0.68))
header.paste(ellipse, point, ellipse)
colortext = '"232,43,123,255"'
pointtext1 = ( int(header.width * 0.845), int(header.height * 0.75))
pointtext2 = ( int(header.width * 0.798), int(header.height * 0.79))
draw.text(pointtext1, "this is some text", font=ImageFont.truetype("C:\Windows\Fonts\Arial.ttf", 14), fill=colortext)
draw.text(pointtext2, "some other text", font=ImageFont.truetype("C:\Windows\Fonts\\arialbd.ttf", 55), fill=colortext)
header.save('Images/header ' + couleur_Ellipse + '.png')
Any insight ? I do not understand why it doesn't work
Conversion of Comment into Answer:
cf: http://pillow.readthedocs.io/en/3.1.x/reference/ImageColor.html
According to the documentation, you need to provide a colour-function (or a hex-colour), rather than just a string of values. And, the colour-function provided as a string doesn't seem to support the alpha value.
Try this:
colortext = "rgb(232,43,123)"

Python append tkinter widget to list shows as int value

I'm trying to make an array/list of tkinter Labels for a wage calculator, but whenever I append the widget to my array, it appends as an int datatype. I was thinking appending it would allow me to call list[widgetIndex].grid() but since it wasn't a Label datatype getting appended to my list for some reason, it gives me an error saying that this 'int' object has no attribute called 'grid'. Why is it an int datatype as oppose to the Label datatype that the variable definitely was before I appended it?
def addJob(jc, cc, he, wl, hl, we):
jc = jc + 1
cc = cc + 2
wageLabel = Label(root, text="Wage")
hoursLabel = Label(root, text="Hours")
wageEntry = Entry(root)
hoursEntry = Entry(root)
wl.append(wageLabel)
hl.append(hoursLabel)
we.append(wageEntry)
he.append(hoursEntry)
wl[jc-1].grid(row =0, column =cc-1, sticky=E)
hl[jc-1].grid(row =1, column =cc-1, sticky=E)
we[jc-1].grid(row = 0, column=cc)
he[jc-1].grid(row = 1, column=cc)
You initialize w1 using w1 = [ 0 ].
Later on you just append to w1, so your list will be sth. like
[ 0, <class 'tkinter.Label'>, <class 'tkinter.Label'>, <class 'tkinter.Label'>, ... ] depending on how many labels you add.
Using w1 = [] will solve your problem.
The error occurs as the first element in your list ("0") cannot be gridded.
Using print w1 in your function would have shown you this in a fairly easy way.
Bryan is right, the code you posted is without a doubt okay for the purpose you intend using it, but the initialization for your passed parameters (not posted as code sample) defines a different behaviour.
Please read on How to create a Minimal, Complete and Verifiable Example. Breaking down code into the smallest piece still reproducing the error mostly guides you direct to the solution.

Raising Image with Tkinter and Python

I have several images that I want to layer in a different order, than the order in which they were created. I am using Python with Tkinter and was wondering if someone could help me with this. The order that I create the images is:
#Using Tkinter
image1 = PhotoImage(file = "imageA.gif")
image2 = PhotoImage(file = "imageB.gif")
image3 = PhotoImage(file = "imageC.gif")
A = canvas.create_image(X,Y,image=image1)
B = canvas.create_image(X,Y,image=image2)
C = canvas.create_image(X,Y,image=image3)
The order in which I create the images cannot be changed, so as of right now C is on top of B which is on top of A.
Is there a way to change the order - without changing the order that I create them - so that B is on top of C, and both on top of A? Perhaps there is some sort of attribute like B.Ontopof(C) ? Thanks for your help in advance.
canvas.tag_raise(item)
at least I think ...

Images in wx.ListControl are cut off

I have a wx.ListCtrl in REPORT mode and i use an image list to display icons which are 50x50 pixels with SetItemColumnImage. The problem now is that the text I display in the column right of the icon is less than 50 pixels high and the parts of the icons that are higher than the text are cut off.
Is there a way to tell ListCtrl to adjust the row height to the height of the icons? Last refuge would be to change the fontsize of the text, but there should be a better way.
Update:
Here is some of my code:
self.list = util.ListCtrl(nb, style=wx.LC_REPORT|
wx.LC_SINGLE_SEL|wx.LC_NO_HEADER|wx.LC_ALIGN_LEFT)
self.list.InsertColumn(0, 'Avatar', width=-1)
self.list.InsertColumn(1, 'Name', width=-1)
self.list.SetColumnWidth(0, 50)
self.imagelist = wx.ImageList(50, 50, 255, 20)
self.list.SetImageList(self.imagelist, wx.IMAGE_LIST_SMALL)
i = 0
for user in self.users:
self.list.Append(['', user['name']])
if user['avatar']:
bitmap = wx.BitmapFromImage(user['avatar'])
imageidx = self.imagelist.Add(bitmap)
self.list.SetItemColumnImage(i, 0, imageidx)
i += 1
When I remove the LC_REPORT flag the images are completely visible but they are all displayed in one row and the names aren't visible anymore.
Since the images are 50x50, I don't think they qualify as "small" any more. Try using the wx.IMAGE_LIST_NORMAL instead of wx.IMAGE_LIST_SMALL. I can't find anything about manually setting row height, so I'm guessing that's not possible. However, I did find a bug report on this topic that says it was resolved in wx2.9. Are you using 2.9?
Alternatively, you could use the UltimateListCtrl which is pure Python and if it doesn't have that ability, you can probably get it patched quickly as the author is very responsive.
Took me a couple cups of coffee to figure it out.
The call to ImageList.Add should precede ListCtrl.Append (or ListCtrl.InsertItem) in order for the ListCtrl to change the height of its rows according to the height of images in ImageList.
So instead of
for user in self.users:
self.list.Append(['', user['name']])
if user['avatar']:
bitmap = wx.BitmapFromImage(user['avatar'])
imageidx = self.imagelist.Add(bitmap)
self.list.SetItemColumnImage(i, 0, imageidx)
You should go with something like this
for user in self.users:
if user['avatar']:
bitmap = wx.BitmapFromImage(user['avatar'])
imageidx = self.imagelist.Add(bitmap)
self.list.Append(['', user['name']])
if user['avatar']:
self.list.SetItemColumnImage(i, 0, imageidx)
Which looks ugly, until you implement a default avatar:
def_avatar = 'default_avatar.jpg'
for user in self.users:
bitmap = wx.BitmapFromImage(user['avatar'] if user['avatar'] else def_avatar)
imageidx = self.imagelist.Add(bitmap)
self.list.Append(['', user['name']])
self.list.SetItemColumnImage(i, 0, imageidx)

Categories