Changing Image.Grab.grab(value) without retyping - python

A list helped me make a loop which grabs a part of the screen and compare it to a existing RGB value. Final code is in final edit. Full learnprocess is shown below.
I'm new to coding in general. I am using pixels do verify RGB value of a pixel which declares position of player. But in stead of re-typing location = ImageGrab.grab(position) can I change the position?
seat0 = (658,848,660,850) #btn
seat1 = (428,816,429,817) #co
seat2 = (406,700,407,701) #hj
seat3 = (546,653,547,654) #lj
seat4 = (798,705,799,706) #bb
seat5 = (769,816,770,817) #sb
btnpos = ImageGrab.grab(seat0)
position = btnpos.load()
btn = (251,0,8)
if position[0,0] == btn:
print('Button')
elif ????
So I want to change seat0 (in imagegrab) to seat1 without re-typing the code. Thanks for the help
EDIT1: So I tried Marks suggestion, not sure what I'm doing wrong.
positie = ["(658,848,660,850)","(428,816,430,818)","(406,700,408,702)","(546,653,548,655)","(798,705,799,706)","(769,816,770,817)"]
btn = (251,0,8)
btnpos = ImageGrab.grab(positie[0])
btncheck = btnpos.load()
btn [0,0] not in positie[0]
I get "ValueError: too many values to unpack (expected 4)"
I am trying to RGB value of positie[0] and it has to match btn. if it doesn't match to btn then it has to check positie[1], until it returns true.
Edit2:
Thanks so far Mark. I am so bad at loops.
positie = [(658,848,660,850),(428,816,430,818),(406,700,408,702),(546,653,548,655),(798,705,799,706),(769,816,770,817)]
btn = (251,0,8)
btnpos = ImageGrab.grab(positie[0])
btncheck = btnpos.load()
for x in positie:
#btncheck = btnpos.load()
if btncheck[0,0] ==btn:
print("positie is BTN")
else:
btnpos = (positie[++1])
print(btnpos)
how do I change btnpos with adding up instead of re-typing everything?
So it's supposed to grab first item in list and compare it to btn. If it's correct it can break, if it's wrong it has to compare btn with second item in list.
If true it gives me the position. If false:
Now it prints list[1] six times.
Thank you for your patience
FINAL EDIT: Thank you Mark.
positie = [(658,848,660,850),(428,816,430,818),(406,700,408,702),(546,653,548,655),(798,705,799,706),(769,816,770,817)]
btn = (251,0,8)
counter = 0
max_index = len(positie) - 1
while counter <= max_index:
btnpos = ImageGrab.grab(positie[counter])
btncheck = btnpos.load()
if btncheck[0,0] == btn:
print("Positie")
break
else:
print("controleert de volgende")
counter = counter + 1

Related

The program adds "" to the string I'm indexing

Im using this piece of code
shares_one = [(None,), ('200 # 496',), ('200 # 486',)]
print(shares_one)
variable_one = StringVar(add_sale_quantity_selector)
variable_one.set(shares_one[1]) # default value
y = OptionMenu(add_sale_quantity_selector, variable_one, *shares_one)
y.place(x=25, y=40)
x = (variable_one.get())
bad_chars = ['"']
for i in bad_chars:
test_string = x.replace(i, '')
print (test_string)
index = shares_one.index(test_string)
print(index)
but it gives me the following error
ValueError: "('200 # 496',)" is not in list
for the line index = shares_one.index(test_string)
whats the possible solution, sorry if anythings out of the picture.

python error - TypeError: string indices must be integers

I have been building a flashcard app and have run into a roadblock while trying to implement a radiobutton. The issue is when run the menu shows up and your able to access the lesson, but the radiobuttons do not appear. Whenever the code is run this error shows up TypeError: string indices must be integers attached to the radiobutton functionbalancing_radio_butto1 = Radiobutton(balancing_frame, text = balancing[answer_list[0]], variable=balancing_radio, value = 1) if someone could explain the why this error shows up as well as how to fix it it would be much appreciated. Below is my code that I have so far.
from tkinter import *
from PIL import ImageTk, Image
from random import branding
import random
root = Tk()
root.title('Chemistry Flashcards')
root.geometry("500x500")
def balancing():
balancing_frame.pack(fill="both", expand=1)
global show_balancing
show_balancing = Label(balancing_frame)
show_balancing.pack(pady=15)
global balancing
balancing = ['balanced1', 'balanced2', 'balanced3', 'balanced4', 'balanced5', 'unbalanced1', 'unbalanced2', 'unbalanced3', 'unbalanced4', 'unbalanced5']
global balancing_state
balancing_state = {
'balanced1':'balanced',
'balanced2':'balanced',
'balanced3':'balanced',
'balanced4':'balanced',
'balanced5':'balanced',
'unbalanced1':'unbalanced',
'unbalanced2':'unbalanced',
'unbalanced3':'unbalanced',
'unbalanced4':'unbalanced',
'unbalanced5':'unbalanced',
}
answer_list = []
count = 1
while count < 3:
rando = randint(0, len(balancing_state)-1)
if count == 1:
answer = balancing[rando]
global balancing_image
balancing = "C:/Users/Kisitu/Desktop/project/balancing/" + balancing[rando] + ".png"
balancing_image = ImageTk.PhotoImage(Image.open(balancing))
show_balancing.config(image=balancing_image)
answer_list.append(balancing[rando])
'''random.shuffle(balancing)'''
count += 1
random.shuffle(answer_list)
global balancing_radio
balancing_radio = IntVar()
balancing_radio_butto1 = Radiobutton(balancing_frame, text = balancing[answer_list[0]], variable=balancing_radio, value = 1)
balancing_radio_butto1.pack(pady=10)
balancing_radio_butto2 = Radiobutton(balancing_frame, text = balancing[answer_list[1]], variable=balancing_radio, value = 2).pack()
my_menu = Menu(root)
root.config(menu=my_menu, bg='#B7F7BB')
lesson_menu = Menu(my_menu)
my_menu.add_cascade(label="Lesson", menu=lesson_menu)
lesson_menu.add_command(label="balancing", command=balancing)
lesson_menu.add_separator()
lesson_menu.add_command(label="Exit", command=root.quit)
balancing_frame = Frame(root, width=500, height=500, )
root.mainloop()
... text = balancing[answer_list[0]] ...
balancing is a list, you are trying to index a value from the list.
you are passing answer_list[0] as index.
answer_list contains random strings from balancing.
you are trying to index a list with a string like in
balancing["balanced2"]
maybe you could use a dictionary?

Searching through html in scrapy?

Is it possible to use a for loop to search through the text of tags that correspond to a certain phrase. I've been trying to create this loop but isn't hasn't been working. Any help is appreciated thanks! Here is my code:
def parse_page(self, response):
titles2 = response.xpath('//div[#id = "mainColumn"]/h1/text()').extract_first()
year = response.xpath('//div[#id = "mainColumn"]/h1/span/text()').extract()[0].strip()
aud = response.xpath('//div[#id="scorePanel"]/div[2]')
a_score = aud.xpath('./div[1]/a/div/div[2]/div[1]/span/text()').extract()
a_count = aud.xpath('./div[2]/div[2]/text()').extract()
c_score = response.xpath('//a[#id = "tomato_meter_link"]/span/span[1]/text()').extract()[0].strip()
c_count = response.xpath('//div[#id = "scoreStats"]/div[3]/span[2]/text()').extract()[0].strip()
info = response.xpath('//div[#class="panel-body content_body"]/ul')
mp_rating = info.xpath('./li[1]/div[2]/text()').extract()[0].strip()
genre = info.xpath('./li[2]/div[2]/a/text()').extract_first()
date = info.xpath('./li[5]/div[2]/time/text()').extract_first()
box = response.xpath('//section[#class = "panel panel-rt panel-box "]/div')
actor1 = box.xpath('./div/div[1]/div/a/span/text()').extract()
actor2 = box.xpath('./div/div[2]/div/a/span/text()').extract()
actor3 = box.xpath('./div/div[3]/div/a/span/text()').extract_first()
for x in info.xpath('//li'):
if info.xpath("./li[x]/div[1][contains(text(), 'Box Office: ')/text()]]
box_office = info.xpath('./li[x]/div[2]/text()')
else if info.xpath('./li[x]/div[1]/text()').extract[0] == "Runtime: "):
runtime = info.xpath('./li[x]/div[2]/time/text()')
Your for loop is completely wrong:
1. You're using info. but searching from the root
for x in info.xpath('.//li'):
2. x is a HTML node element and you can use it this way:
if x.xpath("./div[1][contains(., 'Box Office: ')]"):
box_office = x.xpath('./div[2]/text()').extract_first()
I think you might need re() or re_first() to match the certain phrase.
For example:
elif info.xpath('./li[x]/div[1]/text()').re_first('Runtime:') == "Runtime: "):
runtime = info.xpath('./li[x]/div[2]/time/text()')
And you need to modify your for loop, cuz the variable x in it is actually a Selector but not a number, so it's not right to use it like this: li[x].
gangabass in the last answer made a good point on this.

Setting row Span in QTableView using Python?

I am trying to set rowspan on second column of my QTableView but somehow logically i am missing something. i am only able to get A and B but not C. Plus i am getting warning QTableView::setSpan: span cannot overlap and QTableView::setSpan: single cell span won't be added
My code snippet is:-
startspan = 0
for i, tcname in enumerate(tcfilename):
if tcfilename[i]:
if i > 0:
print '#######################'
print 'startspan = '+str(startspan)+' i = '+str(i)
if tcname == tcfilename[i-1]:
#setSpan (row, column, rowSpan, columnSpan)
print 'if (from_row, till_row) '+str(startspan)+' '+str(i)
table_view.setSpan(startspan, 1, i, 1);
elif tcname != tcfilename[i-1]:
print 'Else no span (from_row, till_row) '+str(startspan)+' '+str(i)
table_view.setSpan(startspan, 1, i, 1);
if i == 1:
startspan = 0
else:
startspan = i
else:
break
Did this with simple two line code below
for toRow, tcname in enumerate(tcfilename):
table_view.setSpan(tcfilename.index(tcname), 1, tcfilename.count(tcname), 1)
I made a nifty little function to solve this.. Had recursion but then optimized it without recursion.. feed it a table and a data set
def my_span_checker(self, my_data, table):
for i in range(len(my_data)):
my_item_count = 0
my_label = table.item(i, 0).text()
for j in range(len(my_data)):
if table.item(j, 0).text() == my_label:
my_item_count += 1
if my_item_count != 1:
table.setSpan(i, 0, my_item_count, 1)

Freeze cells in excel using xlwt

I am creating worksheets on a fly and not naming them anything. I am unable to freeze the first column and row. I tired working with naming the sheet when adding it to the workbook and it works. However doesn't work on the fly. Below is the code
base = xlwt.Workbook()
for k,v in MainDict.items():
base.add_sheet(k.upper())
col_width = 256 * 50
xlwt.add_palette_colour("custom_colour", 0x21)
pattern = 'url:(.*)'
search = re.compile(pattern)
base.set_colour_RGB(0x21, 251, 228, 228)
style = xlwt.easyxf('pattern: pattern solid, fore_colour custom_colour;font : bold on;alignment: horiz center;font: name Times New Roman size 20;font:underline single')
index = MainDict.keys().index(k)
ws = base.get_sheet(index)
ws.set_panes_frozen(True)
try:
for i in itertools.count():
ws.col(i).width = col_width
except ValueError:
pass
style1 = xlwt.easyxf('font: name Times New Roman size 15')
style2 = xlwt.easyxf('font : bold on;font: name Times New Roman size 12')
col=0
for sk in MainDict[k].keys():
ws.write(0,col,sk.upper(),style)
col+=1
row =1
for mk in MainDict[k][sk].keys():
for lk,lv in MainDict[k][sk][mk].items():
for items in lv:
text = ('%s URL: %s')%(items,lk)
links =('No data Found. Please visit the URL: %s')% (lk)
url = re.findall(pattern,text)
if len(items) != 0:
if re.match(pattern,text)==True:
ws.write(row,col-1,url,style2)
else:
ws.write(row,col-1,text,style1)
row+=1
else:
ws.write(row,col-1,links,style2)
#ws.Column(col-1,ws).width = 10000
row+=1
default_book_style = base.default_style
default_book_style.font.height = 20 * 36
base.save('project7.xls')
You have to use
ws.set_panes_frozen(True)
ws.set_horz_split_pos(1)
ws.set_vert_split_pos(1)
to make frozen take effect.
The reason this isn't working may be the result of the "get_sheet() function. Instead, store the add_sheet() call to "ws" and use that:
#base.add_sheet(k.upper())
ws = base.add_sheet(k.upper())
And then you need this sequence of attributes to freeze top row:
#ws = base.get_sheet(index)
#ws.set_panes_frozen(True)
ws.set_horz_split_pos(1)
ws.set_vert_split_pos(1)
ws.panes_frozen = True
ws.remove_splits = True
I tested this using your code snippet and it works on my end.
For reference, you can set these attributes either via function or as assignment:
ws.set_panes_frozen(True)
ws.set_remove_splits(True)

Categories