Weird python/tkinter error - python

So I have this code:
from urllib2 import *
import re
import tkSimpleDialog
import os
import glob
from Tkinter import *
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
image1 = PhotoImage(file="picture.gif")
w = image1.width()
h = image1.height()
master.geometry("%dx%d+0+0" % (w, h))
# tk.Frame has no image argument
panel1 = Label(master, image=image1)
panel1.pack(side='top', fill='both', expand='yes')
panel1.image = image1
self.e = Entry(frame)
self.e.grid(row=0, column=0)
b = Button(frame, text='Search', command=self.whale)
b.grid(row=0, column=1)
###
def whale(self):
page = '1'
def newre():
page = '1'
pages = int(page)
peg = pages + 1
pege = str(peg)
page = pege
self.whale()
alist = []
mu = self.e.get()
print mu
mus = mu.replace(' ','-')
op = urlopen('http://website' + mus + '-'+page+'.html')
ops = op.read()
if 'charset="utf-8">var playlist' in ops:
print 'yes'
cal = ops.split('charset="utf-8">var playlist',1)
del cal[0]
cv = str(cal)
cals = cv.split('},];</script><div',1)
del cals[1]
cals = str(cals)
v = cals.replace('{', '''
''')
vn = v.replace('[','')
vnm = vn.replace(']','')
parsed = re.findall('author : "([^"]+)",title : "([^"]+)",type : "([^"]+)",file : "([^"]+)",id : "([^"]+)', vnm)
print mus
cvb0 = ','.join(map(''.join,parsed[0]))
cvb1 = ','.join(map(''.join,parsed[1]))
cvb2 = ','.join(map(''.join,parsed[2]))
cvb3 = ','.join(map(''.join,parsed[3]))
cvb4 = ','.join(map(''.join,parsed[4]))
cvb5 = ','.join(map(''.join,parsed[5]))
cvb6 = ','.join(map(''.join,parsed[6]))
cvb7 = ','.join(map(''.join,parsed[7]))
cvb8 = ','.join(map(''.join,parsed[8]))
cvb9 = ','.join(map(''.join,parsed[9]))
canada0 = cvb0.split('sound,',1)
canada1 = cvb1.split('sound,',1)
canada2 = cvb2.split('sound,',1)
canada3 = cvb3.split('sound,',1)
canada4 = cvb4.split('sound,',1)
canada5 = cvb5.split('sound,',1)
canada6 = cvb6.split('sound,',1)
canada7 = cvb7.split('sound,',1)
canada8 = cvb8.split('sound,',1)
canada9 = cvb9.split('sound,',1)
song0 = canada0[0]
song1 = canada1[0]
song2 = canada2[0]
song3 = canada3[0]
song4 = canada4[0]
song5 = canada5[0]
song6 = canada6[0]
song7 = canada7[0]
song8 = canada8[0]
song9 = canada9[0]
del canada0[0]
del canada1[0]
del canada2[0]
del canada3[0]
del canada4[0]
del canada5[0]
del canada6[0]
del canada7[0]
del canada8[0]
del canada9[0]
run0 = str(canada0)
run1 = str(canada1)
run2 = str(canada2)
run3 = str(canada3)
run4 = str(canada4)
run5 = str(canada5)
run6 = str(canada6)
run7 = str(canada7)
run8 = str(canada8)
run9 = str(canada9)
#run0
runs0 = str(run0)
nun0 = runs0.split(',',1)
del nun0[1]
nun0 = str(nun0)
run0 = nun0.replace('[','')
runs0 = run0.replace(']','')
runss0 = runs0.replace('"','')
runsss0 = runss0.replace("'",'')
#run1
runs1 = str(run1)
nun1 = runs1.split(',',1)
del nun1[1]
nun1 = str(nun1)
run1 = nun1.replace('[','')
runs1 = run1.replace(']','')
runss1 = runs1.replace('"','')
runsss1 = runss1.replace("'",'')
#run2
runs2 = str(run2)
nun2 = runs2.split(',',1)
del nun2[1]
nun2 = str(nun2)
run2 = nun2.replace('[','')
runs2 = run2.replace(']','')
runss2 = runs2.replace('"','')
runsss2 = runss2.replace("'",'')
#run3
runs3 = str(run3)
nun3 = runs3.split(',',1)
del nun3[1]
nun3 = str(nun3)
run3 = nun3.replace('[','')
runs3 = run3.replace(']','')
runss3 = runs3.replace('"','')
runsss3 = runss3.replace("'",'')
#run4
runs4 = str(run4)
nun4 = runs4.split(',',1)
del nun4[1]
nun4 = str(nun4)
run4 = nun4.replace('[','')
runs4 = run4.replace(']','')
runss4 = runs4.replace('"','')
runsss4 = runss4.replace("'",'')
#run5
runs5 = str(run5)
nun5 = runs5.split(',',1)
del nun5[1]
nun5 = str(nun5)
run5 = nun5.replace('[','')
runs5 = run5.replace(']','')
runss5 = runs5.replace('"','')
runsss5 = runss5.replace("'",'')
#run6
runs6 = str(run6)
nun6 = runs6.split(',',1)
del nun6[1]
nun6 = str(nun6)
run6 = nun6.replace('[','')
runs6 = run6.replace(']','')
runss6 = runs6.replace('"','')
runsss6 = runss6.replace("'",'')
#run7
runs7 = str(run7)
nun7 = runs7.split(',',1)
del nun7[1]
nun7 = str(nun7)
run7 = nun7.replace('[','')
runs7 = run7.replace(']','')
runss7 = runs7.replace('"','')
runsss7 = runss7.replace("'",'')
#run8
runs8 = str(run8)
nun8 = runs8.split(',',1)
del nun8[1]
nun8 = str(nun8)
run8 = nun8.replace('[','')
runs8 = run8.replace(']','')
runss8 = runs8.replace('"','')
runsss8 = runss8.replace("'",'')
#run9
runs9 = str(run9)
nun9 = runs9.split(',',1)
del nun9[1]
nun9 = str(nun9)
run9 = nun9.replace('[','')
runs9 = run9.replace(']','')
runss9 = runs9.replace('"','')
runsss9 = runss9.replace("'",'')
def download0():
print 'downloading...'
url = runsss0
down = urlopen(url)
filepath = 'C:\Users\Psao\Desktop\whalewhire\Downloaded\ ' + song0 + '.mp3'
local = open(filepath, "wb")
local.write(down.read())
print 'done'
def download1():
print 'downloading...'
url = runsss1
down = urlopen(url)
filepath = 'C:\Users\Psao\Desktop\whalewhire\Downloaded\ ' + song1 + '.mp3'
local = open(filepath, "wb")
local.write(down.read())
print 'done'
def download2():
print 'downloading...'
url = runsss2
down = urlopen(url)
filepath = 'C:\Users\Psao\Desktop\whalewhire\Downloaded\ ' + song2 + '.mp3'
local = open(filepath, "wb")
local.write(down.read())
print 'done'
def download3():
print 'downloading...'
url = runsss3
down = urlopen(url)
filepath = 'C:\Users\Psao\Desktop\whalewhire\Downloaded\ ' + song3 + '.mp3'
local = open(filepath, "wb")
local.write(down.read())
print 'done'
def download4():
print 'downloading...'
url = runsss4
down = urlopen(url)
filepath = 'C:\Users\Psao\Desktop\whalewhire\Downloaded\ ' + song4 + '.mp3'
local = open(filepath, "wb")
local.write(down.read())
print 'done'
def download5():
print 'downloading...'
url = runsss5
down = urlopen(url)
filepath = 'C:\Users\Psao\Desktop\whalewhire\Downloaded\ ' + song5 + '.mp3'
local = open(filepath, "wb")
local.write(down.read())
print 'done'
def download6():
print 'downloading...'
url = runsss6
down = urlopen(url)
filepath = 'C:\Users\Psao\Desktop\whalewhire\Downloaded\ ' + song6 + '.mp3'
local = open(filepath, "wb")
local.write(down.read())
print 'done'
def download7():
print 'downloading...'
url = runsss7
down = urlopen(url)
filepath = 'C:\Users\Psao\Desktop\whalewhire\Downloaded\ ' + song7 + '.mp3'
local = open(filepath, "wb")
local.write(down.read())
print 'done'
def download8():
print 'downloading...'
url = runsss8
down = urlopen(url)
filepath = 'C:\Users\Psao\Desktop\whalewhire\Downloaded\ ' + song8 + '.mp3'
local = open(filepath, "wb")
local.write(down.read())
print 'done'
def download9():
print 'downloading...'
url = runsss9
down = urlopen(url)
filepath = 'C:\Users\Psao\Desktop\whalewhire\Downloaded\ ' + song9 + '.mp3'
local = open(filepath, "wb")
local.write(down.read())
print 'done'
def replay():
Admin.destroy()
os.system('WhaleWire.py')
def library():
path = 'C:\Users\Psao\Desktop\whalewhire\Downloaded'
aw=[]
for infile in glob.glob( os.path.join(path,'*.mp3') ):
libr = infile.split('Downloaded',1)
aw.append('\n')
aw.append(infile)
la = Label(Admin,width=100,height=50, text=aw).grid(row=0,column=7)
b2s = Button(Admin,text='Search', command=replay).grid(row=0,column=8)
print song1
Label(Admin, text=song0).grid(row=1)
Label(Admin, text=song1).grid(row=2)
Label(Admin, text=song2).grid(row=3)
Label(Admin, text=song3).grid(row=4)
Label(Admin, text=song4).grid(row=5)
Label(Admin, text=song5).grid(row=6)
Label(Admin, text=song6).grid(row=7)
Label(Admin, text=song7).grid(row=8)
Label(Admin, text=song8).grid(row=9)
Label(Admin, text=song9).grid(row=10)
b0 = Button(Admin, text='Download', command=download0)
b1 = Button(Admin, text='Download', command=download1)
b2 = Button(Admin, text='Download', command=download2)
b3 = Button(Admin, text='Download', command=download3)
b4 = Button(Admin, text='Download', command=download4)
b5 = Button(Admin, text='Download', command=download5)
b6 = Button(Admin, text='Download', command=download6)
b7 = Button(Admin, text='Download', command=download7)
b8 = Button(Admin, text='Download', command=download8)
b9 = Button(Admin, text='Download', command=download9)
b10 = Button(Admin, text='More results', command=newre)
b11 = Button(Admin, text='Library', command=library)
b0.grid(row=1, column=1)
b1.grid(row=2, column=1)
b2.grid(row=3, column=1)
b3.grid(row=4, column=1)
b4.grid(row=5, column=1)
b5.grid(row=6, column=1)
b6.grid(row=7, column=1)
b7.grid(row=8, column=1)
b8.grid(row=9, column=1)
b9.grid(row=10, column=1)
b10.grid(row=10, column=2)
b11.grid(row=11, column=3)
Admin = Tk()
Admin.title('WhaleWires')
app = App(Admin)
Admin.mainloop()
I know it's really long and really repetitive, but i don't want to take the time to find a clean code for each thing.
Any way when I type in a song under two words it give me an error that vary of
an Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "C:\Users\Psao\Desktop\whalewhire\WhaleWire.py", line 93, in whale
cvb7 = ','.join(map(''.join,parsed[7]))
IndexError: list index out of range
but the parse[#] is somtimes diffrent
any help and also if you know any code that would shorten my code I would be greatful.

it seems that parsed is some times shorter than 10 items
the 0-9 variables should be in a list rather than as individual variables this would allow one to use a loop to repeat the same actions on the values rather than duplicating the code for each variable

Related

How can I temporary pause a thread in Python

I am trying write somwthing like messenger with built-in stegonagraphy. Idea is simple: when I send a text it switch it to images, when find a specified pixel in my program. But I have a problem with multithreading mechanism. I worte two methods: receive and write. They are working with excahnging some different commands. Also receive is in separated thread, so I can listen forever. But commands, that should intercept send method are intercepted by recieve method and nothing is happen. My idea is to temporary pause "receive" until I send all, that I need. This is my code for client (server also have same methods):
Client's side code:
import socket
from tkinter import *
import tkinter.scrolledtext as scrolledtext
import threading
from tkinter import filedialog as fd
import time
HOST = '192.168.1.11' #my ip
PORT = 1234
SEPARATOR = '<SEPARATOR>'
BUFFER_SIZE = 1024
class Client:
def __init__(self, host, port):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((host, port))
self.gui_done = False
self.running = True
self.gui_thread = threading.Thread(target=self.gui_loop)
self.receive_thread = threading.Thread(target=self.receive)
self.gui_thread.start()
self.receive_thread.start();
def gui_loop(self):
self.win = Tk()
self.win.title('Client 2')
self.win.configure(bg="lightgray")
self.chat_label = Label(self.win, text="Chat:", bg="lightgray")
self.chat_label.config(font=("Arial", 12))
self.chat_label.pack(padx=20, pady=5)
self.text_area = scrolledtext.ScrolledText(self.win)
self.text_area.pack(padx=20, pady=5)
self.text_area.config(state='disabled')
self.msg_label = Label(self.win, text="Message:", bg="lightgray")
self.msg_label.config(font=("Arial", 12))
self.msg_label.pack(padx=20, pady=5)
self.input_area = Text(self.win, height=5)
self.input_area.pack(padx=20, pady=5)
self.send_button = Button(self.win, text="Send", command=self.write)
self.send_button.config(font=("Arial", 12))
self.send_button.pack(padx=20, pady=5)
self.gui_done = True
self.win.protocol("WM_DELETE_WINDOW", self.stop)
self.win.mainloop()
def write(self):
self.receive_thread.pause();
for i in range(0,4):
#---------Send command---------
print('Connected...')
time.sleep(0.1);
self.sock.sendall('send'.encode());
#---------Read file------------
filename = (str(i+1) + '.jpg')
if i==3:
filename = 'end.jpg'
data = None
with open(filename, 'rb') as f:
data = f.read()
#--------Beginning sending process--------------
while True:
cmd = self.sock.recv(32).decode();
if cmd:
print(cmd);
#---------Receiving sendok-----
if cmd == "sendok":
self.sock.sendall('finfo'.encode());
temp = (str(filename) +'<SEPARATOR>' + '%16d' % len(data)).encode();
print(temp);
self.sock.sendall(temp);
#--------Receiving finfok------
if cmd == "finfok":
self.sock.sendall('img'.encode());
self.sock.sendall(data)
print('File transmission done.')
break
self.sock.sendall('end'.encode());
self.receive_thread.start(self.sock);
def stop(self):
self.running = False
self.win.destroy()
self.sock.close()
exit(0)
def receive(self):
while True:
print('[cmd] Waiting for command...')
command = self.sock.recv(32).decode()
if command:
print('[cmd] ' + command)
if command == 'send':
command = None
self.sock.sendall(b'sendok')
if command == 'finfo':
command = None
finfo = self.sock.recv(1024).decode()
print(finfo)
if SEPARATOR not in finfo:
self.sock.sendall(b'finfo_error')
break
else:
filename, filesize = finfo.split(SEPARATOR)
filesize = int(filesize)
self.sock.sendall(b'finfok')
if command == 'img':
command = None
print('[img] File name: ' + filename + ' | File size: ' + str(filesize) + '.')
file = open(filename, 'wb')
recvd = b''
while filesize > len(recvd):
data = self.sock.recv(BUFFER_SIZE)
if not data:
break
recvd += data
file.write(data)
print('[rcv] Received ' + str(len(recvd)) + '/' + str(filesize) + '.')
if command == 'end':
command = None
client = Client(HOST, PORT)
Server's code
from tkinter import *
from tkinter import scrolledtext
import threading
import socket
import time
HOST_IP = '192.168.1.11'
HOST_PORT = 1234
SEPARATOR = '<SEPARATOR>'
BUFFER_SIZE = 1024
NUMS_OF_CLIENT = 1
class Server:
def __init__(self, host, port):
self.gui_thread = threading.Thread(target=self.gui_loop)
self.gui_thread.start()
self.host = host
self.port = port
self.client_info = None
self.socket_client = None
self.socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket_server.bind((self.host, self.port))
self.socket_server.listen(NUMS_OF_CLIENT)
print('[*] Waiting for client to connect')
self.socket_client, self.client_info = self.socket_server.accept()
print('[+] Client (' + str(self.client_info[0]) + ') connected.')
self.receive_thread.start(self.socket_client);
self.gui_done = False
gui_thread = threading.Thread(target=self.gui_loop)
gui_thread.start()
self.running = True
def receive(self):
while True:
print('[cmd] Waiting for command...')
command = self.socket_client.recv(32).decode()
if command:
print('[cmd] ' + command)
if command == 'send':
command = None
self.socket_client.sendall(b'sendok')
if command == 'finfo':
command = None
finfo = self.socket_client.recv(1024).decode()
if SEPARATOR not in finfo:
self.socket_client.sendall(b'finfo_error')
break
else:
filename, filesize = finfo.split(SEPARATOR)
filesize = int(filesize)
self.socket_client.sendall(b'finfok')
if command == 'img':
command = None
print('[img] File name: ' + filename + ' | File size: ' + str(filesize) + '.')
file = open(filename, 'wb')
recvd = b''
while filesize > len(recvd):
data = self.socket_client.recv(BUFFER_SIZE)
if not data:
break
recvd += data
file.write(data)
print('[rcv] Received ' + str(len(recvd)) + '/' + str(filesize) + '.')
if command == 'end':
command = None
command = None
def send(self):
self.receive_thread.pause();
for i in range(6,10):
#---------Send command---------
print('Connected...')
time.sleep(0.1);
self.socket_client.sendall('send'.encode());
#---------Read file------------
filename = (str(i+1) + '.jpg')
if i==3:
filename = 'end.jpg'
data = None
with open(filename, 'rb') as f:
data = f.read()
#--------Beginning sending process--------------
while True:
cmd = self.socket_client.recv(32).decode();
if cmd:
print(cmd);
#---------Receiving sendok-----
if cmd == "sendok":
self.socket_client.sendall('finfo'.encode());
temp = (str(filename) +'<SEPARATOR>' + '%16d' % len(data)).encode();
print(temp);
self.socket_client.sendall(temp);
#--------Receiving finfok------
if cmd == "finfok":
self.socket_client.sendall('img'.encode());
self.socket_client.sendall(data)
print('File transmission done.')
break
self.sock.sendall('end'.encode());
self.receive_thread.start(self.sock);
def send_th(self):
send_thread = threading.Thread(target = self.send)
send_thread.start()
## self.receive_thread.
def exit(self):
print('[*] Disconnecting...')
try:
self.socket_client.close()
self.socket_server.close()
except:
self.socket_server.close()
finally:
print('[-] Disconnected111111.')
print('[-] Disconnected.')
def gui_loop(self):
self.win = Tk();
self.win.title("Client 1.0");
self.win.configure(bg="lightgray");
self.chat_label = Label(self.win, text="Chat:", bg="lightgray")
self.chat_label.config(font=("Arial", 12))
self.chat_label.grid(row = 0, column = 0, columnspan = 3)
self.text_area = scrolledtext.ScrolledText(self.win)
self.text_area.grid(row = 1, column = 0, columnspan = 3, rowspan = 5)
self.text_area.config(state='disabled')
self.msg_label = Label(self.win, text="Message:", bg="lightgray")
self.msg_label.config(font=("Arial", 12))
self.msg_label.grid(row = 6, column = 0, columnspan = 3)
self.input_area = Text(self.win, height=5)
self.input_area.grid(row = 7, column = 0, columnspan = 3)
self.start_button = Button(self.win, text="Host")
self.start_button.config(font=("Arial", 12))
self.start_button.grid(row = 8, column = 0)
self.send_button = Button(self.win, text="Send", command = self.send_th)
self.send_button.config(font=("Arial", 12))
self.send_button.grid(row = 8, column = 1)
self.exit_button = Button(self.win, text="Exit", command = self.exit)
self.exit_button.config(font=("Arial", 12))
self.exit_button.grid(row = 8, column = 2)
self.gui_done = True
self.win.protocol("WM_DELETE_WINDOW")
self.win.mainloop()
server = Server(HOST_IP, HOST_PORT)

unable to resolve " line 93, in <module> run() and line 89, in run anuncios.extend(anuncios_da_pagina) TypeError: 'NoneType' object not iterable"

from converter import gif_to_png, image_to_text
from file_helper import dictionary_list_to_csv
from util import get_site_html, get_bsobj_from
def get_anuncio(url_anuncio):
print("Buscando " + url_anuncio)
anuncio = {"url": url_anuncio}
html_anuncio = get_site_html(url_anuncio)
if html_anuncio is None:
return None
obj_anuncio = get_bsobj_from(html_anuncio)
if obj_anuncio is None:
return None
span_visible_phone = obj_anuncio.find(id="visible_phone")
span_codigo_do_anuncio = obj_anuncio.find("span", {"class": "sc-gqjmRU"})
codigo_do_anuncio = span_codigo_do_anuncio.get_text()
#print("Código do anúncio: " + codigo_do_anuncio)
anuncio["codigo"] = codigo_do_anuncio
phone = "Desconhecido"
if (span_visible_phone):
imgurl = span_visible_phone.img['src']
img = get_site_html(imgurl)
if img is None:
return None
gif_name = "images/" + codigo_do_anuncio + '.gif'
localFile = open(gif_name, 'wb')
localFile.write(img.read())
localFile.close()
gif_to_png(gif_name)
phone = image_to_text(gif_name + '.png')
anuncio["phone"] = phone
return anuncio
def get_anuncios(url):
html = get_site_html(url)
if html is None:
return None
bsObj = get_bsobj_from(html)
if bsObj is None:
return None
try:
links_for_anuncios = bsObj.findAll("a", {"class": "OLXad-list-link"})
except AttributeError as e:
print("Erro ao obter lista de anúncios")
print(e)
return None
anuncios = []
for link_anuncio in links_for_anuncios:
anuncio = get_anuncio(link_anuncio['href'])
anuncios.append(anuncio)
print(anuncio)
print(" ")
return anuncios
def run():
url = ""
while url == "":
url = input("Informe a URL desejada: ")
numero_de_paginas = input("Informe a quantidade de páginas: ")
if numero_de_paginas == "":
numero_de_paginas = 1
else:
numero_de_paginas = int(numero_de_paginas)
anuncios = []
for page in range(numero_de_paginas):
pagina_atual = page + 1
print("Obtendo anuncios da pagina " + str(pagina_atual))
url_formatada = url
if pagina_atual > 1:
url_formatada += "&o=" + str(pagina_atual)
anuncios_da_pagina = get_anuncios(url_formatada)
anuncios.extend(anuncios_da_pagina)
dictionary_list_to_csv(anuncios)
run()

Maya script that renders to frame buffer keeps grabbing focus on windows

I have a script in Maya (python) that renders a series of frames to the V-ray frame buffer, one for each render layer. It is working well, but when switching render layers and launching the next render, Maya grabs focus, interrupting whatever task the artist had moved on to while the script was running. I would like this to be a background task. Maya is running on Windows.
import maya
import maya.cmds as cmds
import re
from functools import partial
import sys
from datetime import datetime
global cancel
cancel = 0
print 'batch_review'
def no_cam_window_popup(no_cam_set_list):
#print no_cam_set_list
cmds.window(title = 'WARNING: NO CAMERAS LINKED TO LAYERS', width = 300, height = 75, sizeable = False)
cmds.columnLayout("mainColumn", adjustableColumn = True)
cmds.rowLayout("nameRowLayout01", numberOfColumns = 15, parent = "mainColumn")
cmds.text(label = ("no cam set for layers:"))
for layer in no_cam_set_list:
cmds.text(label = ('' + layer + ', '),font = 'boldLabelFont')
cmds.showWindow()
def renderThumbs(checkBoxLow,checkBoxMid,checkBoxHigh,checkBoxRenderRegion,intField_res,floatField_thrhld,*args):
global cancel
cams = cmds.ls(type = "camera")
cancel = 0
popup_win = 0
no_cam_set_list = []
cmds.loadPlugin('vrayformaya', quiet=True)
cmds.pluginInfo('vrayformaya', edit=True, autoload=True)
cmds.setAttr("defaultRenderGlobals.ren", "vray", type = "string")
curLay = cmds.editRenderLayerGlobals( currentRenderLayer = True, query = True )
changeLay = curLay
rls = cmds.ls(type = "renderLayer")
renCams = cmds.ls(type = "camera")
renCam = "persp"
lowBut = cmds.checkBox(checkBoxLow,value = True, query = True)
midBut = cmds.checkBox(checkBoxMid,value = True, query = True)
highBut = cmds.checkBox(checkBoxHigh,value = True, query = True)
globopt_cache_geom_plugins = cmds.getAttr('vraySettings.globopt_cache_geom_plugins')
#print 'globopt_cache_geom_plugins = ',globopt_cache_geom_plugins
print " "
print "-- batch_review --"
res = cmds.intField(intField_res, v = True, query = True)
thr = cmds.floatField(floatField_thrhld, v = True,query = True)
if lowBut == 1:
cmds.setAttr("vraySettings.dmcThreshold",thr)
cmds.setAttr("vraySettings.width", res)
cmds.setAttr("vraySettings.height", res)
cmds.setAttr("vraySettings.globopt_cache_geom_plugins",1)
cmds.setAttr("vraySettings.globopt_ray_maxIntens_on",1)
#cmds.setAttr('vraySettings.globopt_cache_geom_plugins',globopt_cache_geom_plugins)
print " "
print "---"
print "quality = %s, dmcThreshold = %s"%(res,thr)
if midBut == 1:
cmds.setAttr("vraySettings.dmcThreshold",thr)
cmds.setAttr("vraySettings.width", res)
cmds.setAttr("vraySettings.height", res)
cmds.setAttr("vraySettings.globopt_cache_geom_plugins",1)
cmds.setAttr("vraySettings.globopt_ray_maxIntens_on",1)
#cmds.setAttr('vraySettings.globopt_cache_geom_plugins',globopt_cache_geom_plugins)
print " "
print "---"
print "quality = %s, dmcThreshold = %s"%(res,thr)
if highBut == 1:
cmds.setAttr("vraySettings.dmcThreshold",thr)
cmds.setAttr("vraySettings.width", res)
cmds.setAttr("vraySettings.height", res)
cmds.setAttr("vraySettings.globopt_cache_geom_plugins",1)
cmds.setAttr("vraySettings.globopt_ray_maxIntens_on",1)
#cmds.setAttr('vraySettings.globopt_cache_geom_plugins',globopt_cache_geom_plugins)
print " "
print "---"
print "quality = %s, dmcThreshold = %s"%(res,thr)
print "--- "
print " "
for rl in rls:
found_cam = 0
if rl != "defaultRenderLayer" and cancel == 0:
rlState = cmds.getAttr(rl + ".renderable")
if rlState == 1:
print ' '
print "rende layer = ",rl
cmds.editRenderLayerGlobals( currentRenderLayer = rl )
for cam in cams:
camState = cmds.getAttr(cam + ".renderable")
if camState == 1:
rrState = cmds.checkBox(checkBoxRenderRegion,value = True,query = True)
reg = cmds.vray("vfbControl","-getregion")
if rrState == 0:
cmds.vray("vfbControl","-setregion","reset")
if rrState == 1:
cmds.vray("vfbControl","-setregionenabled",1)
cmds.vray("vfbControl","-setregion",reg[0],reg[1],reg[2],reg[3])
mayaString = "renderWindowRenderCamera render renderView " + cam
print 'using ' + cam + ' for ' + rl
maya.mel.eval(mayaString)
cmds.vray("vfbControl", "-historysave")
cmds.vray("vfbControl", "-historyselect",0)
dte = datetime.now().strftime('%H:%M:%S')
editStr = dte + " ,render layer: " + rl + " , " + "cam: " + cam
cmds.vray("vfbControl", "-historycomment", editStr)
print " "
found_cam = 1
if found_cam == 0:
print 'no camera link found, using persp cam for ',rl
cam = 'persp'
rrState = cmds.checkBox(checkBoxRenderRegion,value = True,query = True)
reg = cmds.vray("vfbControl","-getregion")
if rrState == 0:
cmds.vray("vfbControl","-setregion","reset")
if rrState == 1:
cmds.vray("vfbControl","-setregionenabled",1)
cmds.vray("vfbControl","-setregion",reg[0],reg[1],reg[2],reg[3])
mayaString = "renderWindowRenderCamera render renderView " + cam
maya.mel.eval(mayaString)
cmds.vray("vfbControl", "-historysave")
cmds.vray("vfbControl", "-historyselect",0)
dte = datetime.now().strftime('%H:%M:%S')
editStr = dte + " ,render layer: " + rl + " , " + "cam: " + cam
cmds.vray("vfbControl", "-historycomment", editStr)
popup_win = 1
no_cam_set_list.append(rl)
#if popup_win == 1:
#no_cam_window_popup(no_cam_set_list)
def checkBoxCheckLow(checkBoxLow,checkBoxMid,checkBoxHigh,intField_res,floatField_thrhld,*args):
global cancel
lowButVal = cmds.checkBox(checkBoxLow,value = True, query = True)
midButVal = cmds.checkBox(checkBoxMid,value = True, query = True)
highButVal = cmds.checkBox(checkBoxHigh,value = True, query = True)
cmds.checkBox(checkBoxMid,value = False, edit = True)
cmds.checkBox(checkBoxHigh,value = False, edit = True)
cmds.intField(intField_res, v = 800,edit = True)
cmds.floatField(floatField_thrhld, v = .1,edit = True )
cancel = 0
def checkBoxCheckMid(checkBoxLow,checkBoxMid,checkBoxHigh,intField_res,floatField_thrhld,*args):
global cancel
lowButVal = cmds.checkBox(checkBoxLow,value = True, query = True)
midButVal = cmds.checkBox(checkBoxMid,value = True, query = True)
highButVal = cmds.checkBox(checkBoxHigh,value = True, query = True)
cmds.checkBox(checkBoxLow,value = False, edit = True)
cmds.checkBox(checkBoxHigh,value = False, edit = True)
cmds.intField(intField_res, v = 1000,edit = True)
cmds.floatField(floatField_thrhld, v = .5,edit = True )
cancel = 0
def checkBoxCheckHigh(checkBoxLow,checkBoxMid,checkBoxHigh,intField_res,floatField_thrhld,*args):
global cancel
lowButVal = cmds.checkBox(checkBoxLow,value = True, query = True)
midButVal = cmds.checkBox(checkBoxMid,value = True, query = True)
highButVal = cmds.checkBox(checkBoxHigh,value = True, query = True)
cmds.checkBox(checkBoxLow,value = False, edit = True)
cmds.checkBox(checkBoxMid,value = False, edit = True)
cmds.intField(intField_res, v = 2000,edit = True)
cmds.floatField(floatField_thrhld, v = .008,edit = True )
cancel = 0
def checkBoxAOVchange(checkBoxAOV,*args):
checkBoxAOVval = cmds.checkBox(checkBoxAOV,value = True,query = True)
if checkBoxAOVval == 1:
cmds.setAttr("vraySettings.relements_enableall", 1)
if checkBoxAOVval == 0:
cmds.setAttr("vraySettings.relements_enableall", 0)
def rrCheckbox(checkBoxRenderRegion,reg,*args):
global gReg
zeroes = ['0','0','0','0']
tRes = cmds.vray("vfbControl","-getregion")
if tRes != zeroes:
gReg = tRes
rrstate = cmds.checkBox(checkBoxRenderRegion,value = True,query = True)
if rrstate == 0:
if gReg != zeroes:
cmds.vray("vfbControl","-setregion",gReg[0],gReg[1],gReg[2],gReg[3])
else:
cmds.vray("vfbControl","-setregion",reg[0],reg[1],reg[2],reg[3])
cmds.vray("vfbControl","-setregion","reset")
if rrstate == 1:
cmds.vray("vfbControl","-setregionenabled",1)
if gReg != zeroes:
cmds.vray("vfbControl","-setregion",gReg[0],gReg[1],gReg[2],gReg[3])
else:
cmds.vray("vfbControl","-setregion",reg[0],reg[1],reg[2],reg[3])
return(reg)
def cancelOPs(*args):
global cancel
cancel = 1
raise Exception("quitting renders")
def set_threshhold(floatField_thrhld,*args):
threshhold_value = cmds.floatField(floatField_thrhld,value = True,query = True)
cmds.setAttr('vraySettings.dmcThreshold',threshhold_value)
def set_resolution(intField_res,*args):
intField_res_value = cmds.intField(intField_res,value = True,query = True)
cmds.setAttr('vraySettings.width',intField_res_value)
cmds.setAttr('vraySettings.height',intField_res_value)
def renthumbsWin():
name = "Batch_Review"
global gReg
gReg = ('0','0','0','0')
zeroes = ('0','0','0','0')
windowSize = (200,100)
if (cmds.window(name, exists = True)):
cmds.deleteUI(name)
window = cmds.window(name, title = name, width = 350, height = 50,bgc = (.2,.2,.2), s = False)
cmds.columnLayout("mainColumn", adjustableColumn = True)
cmds.rowLayout("nameRowLayout01", numberOfColumns = 15, parent = "mainColumn")
cmds.text(label = "preset quality: ")
checkBoxLow = cmds.checkBox(label = "low", value = False)
checkBoxMid = cmds.checkBox(label = "mid", value = True,)
checkBoxHigh = cmds.checkBox(label = "high", value = False)
cmds.text(label = " ")
cmds.text(label = "resolution: ")
intField_res = cmds.intField(v = 1000,width = 45)
#print 'intField_res = ',intField_res
cmds.intField(intField_res, changeCommand = partial(set_resolution,intField_res),edit = True)
cmds.text(label = " ")
cmds.text(label = "threshold: ")
floatField_thrhld = cmds.floatField(v = .5,width = 45)
cmds.floatField(floatField_thrhld, changeCommand = partial(set_threshhold,floatField_thrhld),edit = True)
cmds.checkBox(checkBoxLow, changeCommand = partial(checkBoxCheckLow,checkBoxLow,checkBoxMid,checkBoxHigh,intField_res,floatField_thrhld), edit = True)
cmds.checkBox(checkBoxMid, changeCommand = partial(checkBoxCheckMid,checkBoxLow,checkBoxMid,checkBoxHigh,intField_res,floatField_thrhld),edit = True)
cmds.checkBox(checkBoxHigh, changeCommand = partial(checkBoxCheckHigh,checkBoxLow,checkBoxMid,checkBoxHigh,intField_res,floatField_thrhld),edit = True)
cmds.rowLayout("nameRowLayout02", numberOfColumns = 10, parent = "mainColumn")
cmds.text(label = " ")
cmds.rowLayout("nameRowLayout03", numberOfColumns = 5, parent = "mainColumn")
renderButton = cmds.button(label = "render",width = 100, bgc = (.6,.8,1) )
cmds.text(label = " ")
cmds.button(label = "cancel renders", command = partial(cancelOPs),bgc = (1,.3,.3) )
cmds.rowLayout("nameRowLayout04", numberOfColumns = 10, parent = "mainColumn")
cmds.text(label = " ")
cmds.rowLayout("nameRowLayout05", numberOfColumns = 10, parent = "mainColumn")
checkBoxRenderRegion = cmds.checkBox(label = "use render region", value = False)
cmds.text(label = " ")
cmds.text(label = " ")
reg = cmds.vray("vfbControl","-getregion")
if reg != gReg and reg != zeroes:
gReg = reg
cmds.vray("vfbControl","-setregion","reset")
cmds.checkBox(checkBoxRenderRegion,changeCommand = partial(rrCheckbox,checkBoxRenderRegion,reg),edit = True)
cmds.rowLayout("nameRowLayout06", numberOfColumns = 10, parent = "mainColumn")
AOVstate = cmds.getAttr("vraySettings.relements_enableall")
checkBoxAOV = cmds.checkBox(label = "elements", value = AOVstate)
cmds.checkBox(checkBoxAOV,changeCommand = partial(checkBoxAOVchange,checkBoxAOV),edit = True)
cmds.button(renderButton,command = partial(renderThumbs,checkBoxLow,checkBoxMid,checkBoxHigh,checkBoxRenderRegion,intField_res,floatField_thrhld),edit = True)
cmds.showWindow()
def main():
renthumbsWin()
main()

exception used to pop up alert box from button event in tkinter, cant find out the root for the problem

so my program takes a directory with excel files with one line and combine them all into one.
The gui has two buttons one to choose the path and one to save the wanted path.
I created a gui class and im basically trying to pass the OptionMenu chosen text forward after an event was made, but an exception is raised and Im struggling with,
long story short:
import os
from tkinter import *
from tkinter import filedialog
from CombineExcelFiles import *
class GUI:
def __init__(self, master):
self.master = master
master.title('מיזוג קבצי אקסל')
master.geometry('220x100')
self.credit = Label(master, text='')
self.credit.pack()
self.variable = StringVar(master)
self.variable.set('חלבי')
self.opt = OptionMenu(master, self.variable, 'חלבי', 'פרווה')
self.opt.pack()
Button(window, text='בחר תיקייה למיזוג', command=upload).pack(side=RIGHT)
Button(window, text='בחר תייקת הורדה', command=save).pack(side=LEFT)
def upload():
global basepath
basepath = filedialog.askdirectory()
def save():
#print(self.variable.get())
try: #This is line 25
basepath
file_list = []
download_path = filedialog.askdirectory()
for entry in os.listdir(basepath):
if os.path.isfile(os.path.join(basepath, entry)):
if entry[len(entry)-5:] == '.xlsx' and len(entry) == 17:
file_list.append(entry)
data = getData(basepath, file_list)
writeToFile(data, file_list, download_path, master.variable.get())
except NameError:
tkinter.messagebox.showerror('ERROR', 'בחר תיקיית מקור')
This is the writeToFile from CombineExcelFiles:
def writeToFile(data, files,download_path,variable):
file = Workbook()
ws = file.active
center = Alignment(horizontal='center', vertical='center')
br = Border(left=Side(style='thin'),
right=Side(style='thin'),
top=Side(style='thin'),
bottom=Side(style='thin'))
.
.
.
col = 'C'
row = 3
count = 0
for i in data:
temp = files[count]
for j in i[::-1]:
if type(j) == int or type(j) == float:
ws[col + str(row)].value = ('%.2f' %j)
ws[col + str(row)].alignment = center
ws[col + str(row)].border = br
col = chr(ord(col)+1)
ws['J' + str(row)].value = temp[6:8] + '/' + temp[4:6] + '/' + temp[:4]
ws['K' + str(row)].value = temp[8:10] + ':' + temp[10:12]
row +=1
col = 'C'
ws = fitToCell(ws)
temp_date = datetime.now()
file.save(download_path + '/' + 'מעקב ' + variable + str(temp_date.month) + '-' +
str(temp_date.year) + '.xlsx' )
The error that was given is:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\******\Anaconda3\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:/Users/******/CombineExcels/mainProject.py", line 25, in save
print(self.variable.get())
TypeError: writeToFile() missing 1 required positional argument: 'variable'
Thank you in advance
Edit, Ive put the code n one file so it will be runnable:
import os
from tkinter import *
from tkinter import filedialog
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.styles import Alignment
from openpyxl.styles.borders import Border, Side
from datetime import datetime
class GUI:
def __init__(self, master):
self.master = master
master.title('מיזוג קבצי אקסל')
master.geometry('220x100')
self.credit = Label(master, text='')
self.credit.pack()
self.variable = StringVar(master)
self.variable.set('בחר מרשימה')
self.opt = OptionMenu(master, self.variable, 'חלבי', 'פרווה')
self.opt.pack()
Button(window, text='בחר תיקייה למיזוג', command=upload).pack(side=RIGHT)
Button(window, text='בחר תייקת הורדה', command=save).pack(side=LEFT)
#START GUI PROPERTIES
def upload(self):
global basepath
basepath = filedialog.askdirectory()
print(master)
def save(self):
file_list = []
download_path = filedialog.askdirectory()
for entry in os.listdir(basepath):
if os.path.isfile(os.path.join(basepath, entry)):
if entry[len(entry)-5:] == '.xlsx' and len(entry) == 17:
file_list.append(entry)
data = getData(basepath, file_list)
print(self.variable.get())
writeToFile(data, file_list, download_path)
#STOP GUI PROPERTIES
def getData(self, basepath, file_list):
a = []
for file in file_list:
load_workbook(basepath + '/' + file)
tempData = []
for cell in temp['Sheet1']:
for value in cell:
if value.value == None:
continue
else:
tempData.append(value.value)
data.append(tempData)
return data
def fitToCell(self, ws): #get used columns and than fit cell's width into length of letters
dict = {}
for cell in ws:
for value in cell:
temp = str(value.value)
if temp:
if value.coordinate[0] not in dict:
dict[value.coordinate[0]] = len(temp)
elif len(temp) > dict[value.coordinate[0]]:
dict[value.coordinate[0]] = len(temp)
for col in dict:
ws.column_dimensions[col].width = dict[col]
return ws
def writeToFile(self, data, files,download_path):
file = Workbook()
ws = file.active
center = Alignment(horizontal='center', vertical='center')
br = Border(left=Side(style='thin'),
right=Side(style='thin'),
top=Side(style='thin'),
bottom=Side(style='thin'))
print(ws.evenHeader.right.text)
if self.variable.get() == 'חלבי':
ws['C2'].value = 'חלב רצוי'
ws['C2'].alignment = center
ws['C2'].border = br
ws['D2'].value = 'חלב מצוי'
ws['D2'].alignment = center
ws['D2'].border = br
ws['E2'].value = 'קקאו רצוי'
ws['E2'].alignment = center
ws['E2'].border = br
ws['F2'].value = 'קקאו מצוי'
ws['F2'].alignment = center
ws['F2'].border = br
ws['G2'].value = 'שמן רצוי'
ws['G2'].alignment = center
ws['G2'].border = br
ws['H2'].value = 'שמן מצוי'
ws['H2'].alignment = center
ws['H2'].border = br
ws['I2'].value = 'סוכר רצוי'
ws['I2'].alignment = center
ws['I2'].border = br
ws['J2'].value = 'סוכר מצוי'
ws['J2'].alignment = center
ws['J2'].border = br
ws['I2'].value = 'מספר מתכון'
ws['I2'].alignment = center
ws['I2'].border = br
ws['J2'].value = 'זמן ייצור'
ws['J2'].alignment = center
ws['J2'].border = br
ws['K2'].value = 'תאריך ייצור'
ws['K2'].alignment = center
ws['K2'].border = br
col = 'C'
row = 3
count = 0
for i in data:
temp = files[count]
for j in i[::-1]:
if type(j) == int or type(j) == float:
ws[col + str(row)].value = ('%.2f' %j)
ws[col + str(row)].alignment = center
ws[col + str(row)].border = br
col = chr(ord(col)+1)
ws['J' + str(row)].value = temp[6:8] + '/' + temp[4:6] + '/' + temp[:4]
ws['J' + str(row)].alignment = center
ws['J' + str(row)].border = br
ws['K' + str(row)].value = temp[8:10] + ':' + temp[10:12]
ws['K' + str(row)].border = br
ws['K' + str(row)].alignment = center
row +=1
col = 'C'
ws = fitToCell(ws)
temp_date = datetime.now()
file.save(download_path + '/' + 'מעקב ' + self.variable.get() +' ' + str(temp_date.month) + '-' + str(temp_date.year) + '.xlsx' )
window = Tk()
my_gui = GUI(window)
#print(my_gui.variable.get())
window.mainloop()
This is the error:
runfile('C:/Users/*****/Desktop/תכנות/untitled2.py',
wdir='C:/Users/*****/Desktop/תכנות')
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\*****\Anaconda3\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:/Users/*****/CombineExcels/mainProject.py", line 25, in save
TypeError: writeToFile() missing 1 required positional argument: 'var'
For some reason it keeps returning from another path
solved it, had put all the methods inside the object, while the events func inside the init.
also i ran too many times the program so the errors were not related to my code...

Tkinter: Adding a scrollbar to a canvas

I'm trying to add a scrollbar to my tkinter window which stays in place and scrolls through a frame. However, whenever I launch the application, the scrollbar is greyed out. Here is the relevant excerpt from my code:
self.bigFrame = ttk.Frame(self,width = 1080,height = 500)
self.hsb = tk.Scrollbar(self.bigFrame,orient = "horizontal")
self.hsb.pack(side = TOP, fill = X)
self.treeCanvas = tk.Canvas(self.bigFrame,width = 1080,height = 500,xscrollcommand = self.hsb.set)
self.treeFrame = tk.Frame(self.treeCanvas,width = 1080,height = 500)
self.treeCanvas.create_window((0,0),window=self.treeFrame,anchor = 'nw')
self.treeCanvas.config(scrollregion = self.treeCanvas.bbox("all"))
self.treeCanvas.pack(side = BOTTOM,fill = X)
self.treeFrame.pack(side = BOTTOM,fill = X)
self.hsb.config(command = self.treeCanvas.xview)
self.tree = ttk.Treeview(self.treeFrame,selectmode='browse',height = 100, columns = ('name','purchaseprice','previousprices','listingprice','buyingformat','postage','fees','potprofit','offers','viewcount','sold','offertaken','username','dispatch','delivered','returned','relist','feedback'))
self.tree.heading('#0',text = 'saleID',anchor = 'w')
self.tree.heading('name',text = "Item Name",anchor = 'w')
self.tree.heading('purchaseprice',text = "Purchase Price",anchor = 'w')
self.tree.heading('previousprices',text = "Previous Prices",anchor = 'w')
self.tree.heading('listingprice',text = "Listing Price", anchor = 'w')
self.tree.heading('buyingformat',text = "Buying Format",anchor = 'w')
self.tree.heading('postage',text = "Postage",anchor = 'w')
self.tree.heading('fees',text = "Fees",anchor = 'w')
self.tree.heading('potprofit',text = "Potential Profit",anchor = 'w')
self.tree.heading('offers',text = "Best Offer",anchor = 'w')
self.tree.heading('viewcount',text = "Viewcount",anchor = 'w')
self.tree.heading('sold',text = "Sold?",anchor = 'w')
self.tree.heading('offertaken',text = "Offer Taken?",anchor = 'w')
self.tree.heading('username',text = "Username",anchor = 'w')
self.tree.heading('dispatch',text = "Dispatched?",anchor = 'w')
self.tree.heading('delivered',text = "Delivered?",anchor = 'w')
self.tree.heading('returned',text = "Returned?",anchor = 'w')
self.tree.heading('relist',text = "Relisted?",anchor = 'w')
self.tree.heading('feedback',text = "Feedback",anchor = 'w')
self.tree.pack(side = BOTTOM, fill = X)
self.bigFrame.grid(row = 11,column = 0,columnspan = 100,pady=(5,0),sticky = 'nw')
self.bigFrame.grid_rowconfigure(0,weight = 1)
self.bigFrame.grid_columnconfigure(0,weight = 1)
self.bigFrame.grid_propagate(False)
I'm sure it's an issue with the ordering of lines, but none of the orders I've tried have worked.
The reason your scrollbar is greyed out is because you are missing this line:
self.treeFrame.update_idletasks()
Below implemented in the rest of your code.
...
self.treeCanvas.create_window((0,0),window=self.treeFrame,anchor = 'nw')
# add this
self.treeFrame.update_idletasks()
bbox = self.treeCanvas.bbox(tk.ALL)
# Update this
self.treeCanvas.config(scrollregion=bbox, width=DISPLAY_WIDTH, height=DISPLAY_HEIGHT)
self.treeCanvas.pack(side = BOTTOM,fill = X)
self.treeFrame.pack(side = BOTTOM,fill = X)
...
Hopefully this answer helps, if not you could try the last answer from this question, which helped me alot.

Categories

Resources